Python|元组列表中第 N 个索引的最小 K 条记录
有时,在处理数据时,我们可能会遇到一个问题,即我们需要获取由记录的第 N 个元素过滤的最少元素。这在 Web 开发领域具有非常重要的实用性。让我们讨论可以执行此任务的某些方式。
方法 #1:使用filter() + lambda + set()
+ 列表推导
上述功能的组合可用于执行此特定函数。在此,我们首先从第 N 个索引中过滤出最少 K 个元素,然后将这些值应用于列表并返回结果。
# Python3 code to demonstrate working of
# Minimum K records of Nth index in tuple list
# Using filter() + lambda + set() + list comprehension
# initialize list
test_list = [('gfg', 4, 'good'), ('gfg', 2, 'better'),
('gfg', 1, 'best'), ('gfg', 3, 'geeks')]
# printing original list
print("The original list is : " + str(test_list))
# initialize N
N = 1
# initialize K
K = 2
# Minimum K records of Nth index in tuple list
# Using filter() + lambda + set() + list comprehension
temp = set(list({sub[N] for sub in test_list})[ :K])
res = list(filter(lambda sub: sub[N] in temp, test_list))
# printing result
print("Min K elements of Nth index are : " + str(res))
The original list is : [(‘gfg’, 4, ‘good’), (‘gfg’, 2, ‘better’), (‘gfg’, 1, ‘best’), (‘gfg’, 3, ‘geeks’)]
Min K elements of Nth index are : [(‘gfg’, 2, ‘better’), (‘gfg’, 1, ‘best’)]
方法#2:使用groupby() + sorted()
+ 循环
也可以使用上述功能执行此任务。在此,我们首先将最小 K 个元素组合在一起,然后在构建结果列表时限制为 K。
# Python3 code to demonstrate working of
# Minimum K records of Nth index in tuple list
# Using groupby() + sorted() + loop
import itertools
# initialize list
test_list = [('gfg', 4, 'good'), ('gfg', 2, 'better'),
('gfg', 1, 'best'), ('gfg', 3, 'geeks')]
# printing original list
print("The original list is : " + str(test_list))
# initialize N
N = 1
# initialize K
K = 2
# Minimum K records of Nth index in tuple list
# Using groupby() + sorted() + loop
res = []
temp = itertools.groupby(sorted(test_list, key = lambda sub : sub[N]),
key = lambda sub : sub[N])
for i in range(K):
res.extend(list(next(temp)[N]))
# printing result
print("Min K elements of Nth index are : " + str(res))
The original list is : [(‘gfg’, 4, ‘good’), (‘gfg’, 2, ‘better’), (‘gfg’, 1, ‘best’), (‘gfg’, 3, ‘geeks’)]
Min K elements of Nth index are : [(‘gfg’, 2, ‘better’), (‘gfg’, 1, ‘best’)]