Python查找列表中最大(最小)的n个元素和它们的索引值

# 需要导入heapq库
import heapq

# 1.获取列表中最大(最小)的n个值
# 语法:heapq.nlargest/nsmallest(n,列表)
result1=heapq.nlargest(3,[1,2,3,4,5])
result2=heapq.nsmallest(3,[1,2,3,4,5])

# 2.获取列表中最大(最小)的n个值的索引
# 语法:list(map(列表名.index,heapq.nlargest(n,列表)))
l=[1,2,3,4,5]
index1=list(map(l.index,heapq.nlargest(3,l)))
index2=list(map(l.index,heapq.nsmallest(3,l)))

你可能感兴趣的:(Python,python)