Python - 列表中具有索引的 K 个最大元素
给定一个列表,提取 K 个最大元素及其索引。
Input : test_list = [5, 3, 1, 4, 7, 8, 2], K = 2
Output : [(4, 7), (5, 8)]
Explanation : 8 is maximum on index 5, 7 on 4th.
Input : test_list = [5, 3, 1, 4, 7, 10, 2], K = 1
Output : [(5, 10)]
Explanation : 10 is maximum on index 5.
方法 #1:使用 sorted() + index()
上述功能的组合提供了一种解决该问题的方法。在此,我们首先执行排序并提取 K 个最大元素,然后将它们封装在元组中,它们在原始列表中的排序。
Python3
# Python3 code to demonstrate working of
# K Maximum elements with Index in List
# Using sorted() + index()
# initializing list
test_list = [5, 3, 1, 4, 7, 8, 2]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 3
# Using sorted() + index()
# using sorted() to sort and slice K maximum elements
temp = sorted(test_list)[-K:]
res = []
for ele in temp:
# encapsulating elements with index using index()
res.append((test_list.index(ele), ele))
# printing result
print("K Maximum with indices : " + str(res))
Python3
# Python3 code to demonstrate working of
# K Maximum elements with Index in List
# Using enumerate() + itemgetter()
from operator import itemgetter
# initializing list
test_list = [5, 3, 1, 4, 7, 8, 2]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 3
# Using enumerate() + itemgetter()
# Making index values pairs at 1st stage
res = list(sorted(enumerate(test_list), key = itemgetter(1)))[-K:]
# printing result
print("K Maximum with indices : " + str(res))
输出
The original list : [5, 3, 1, 4, 7, 8, 2]
K Maximum with indices : [(0, 5), (4, 7), (5, 8)]
方法 #2:使用 enumerate() + itemgetter()
上述功能的组合可以用来解决这个问题。在此,我们使用 enumerate() 执行获取索引的任务,而 itemgetter() 用于获取元素。
Python3
# Python3 code to demonstrate working of
# K Maximum elements with Index in List
# Using enumerate() + itemgetter()
from operator import itemgetter
# initializing list
test_list = [5, 3, 1, 4, 7, 8, 2]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 3
# Using enumerate() + itemgetter()
# Making index values pairs at 1st stage
res = list(sorted(enumerate(test_list), key = itemgetter(1)))[-K:]
# printing result
print("K Maximum with indices : " + str(res))
输出
The original list : [5, 3, 1, 4, 7, 8, 2]
K Maximum with indices : [(0, 5), (4, 7), (5, 8)]