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