有沒有辦法在沒有 foor 循環的情況下計算列表中的 N 個最大元素?def Nlargest(list):
#your code here
#print n largest element of a list without for loop
3 回答

飲歌長嘯
TA貢獻1951條經驗 獲得超3個贊
def Nlargest(list): import heapq print(heapq.nlargest(n,list)) #return a list of n largest element
我希望這會幫助你

胡子哥哥
TA貢獻1825條經驗 獲得超6個贊

繁星點點滴滴
TA貢獻1803條經驗 獲得超3個贊
您可以對列表進行排序并打印最后 n 個元素(列表中最大的 n 個元素),如下所示
def Nlargest(list):
list.sort() # first sort the list
print(list[-n:]) # print the last n elements as they will be the largest ones
上面代碼(不會改變原始列表)的簡寫是 -
def Nlargest(list):
print(sorted(list, reverse=True)[:n]) #sort in descending order and print first n elements
希望這可以幫助 !
添加回答
舉報
0/150
提交
取消