2016-11-20 82 views
2

我原本兩個數組,一個包含數字,其他關聯值:查找最長的子表的索引中2D列表

scores = [2,   4,  12 ... etc ] 
players = ["Peter", "Brian", "Meg" ... etc] 
top_score_index = scores.index(max(scores)) 
top_player = players[top_score_index] 

這已經太臭,因爲scores.index(max(scores))明顯(超過該列表迭代兩次最壞的情況)。

情況發生了變化,在scores數組現在包含列表:

scores = [[something, something, something], [something, something]] 

這是我關心的得分然而僅僅len(scores[some_offset]),那就是嵌套列表的長度。

如何輕鬆找到這些嵌套列表中最長的索引?例如。用於:

[[0,0,0],[0,0],[0,0,0,0,0,0]] 

我期望返回值爲2。請現在對我來說效率問題

回答

4
scores = [[0,0,0],[0,0],[0,0,0,0,0,0]] 
print(max((len(l), i) for i, l in enumerate(scores))[1]) 

打印2

您無法避免在每個子列表上撥打len,所以我認爲您無法在效率上做得更好。

+0

如果我理解正確,分數= [[0,0,0],[0,0],[0,0,0,0,0,0],[0,0,0 ,0,0,0]]'這將輸出'3',即_last_發生的最大值。爲了得到_first_,你可以使用'print(-max((len(l),-i)for i,l in enumerate(scores)] [1])' –

+0

是的,那會工作得到索引第一個具有最大長度的子列表。 – cco

1

使用enumerate()獲得(idx, value)元組,同時迭代樂譜。

idx, max_val = 0, len(scores[0]) 
for idx, sublst in enumerate(scores): 
    if len(sublst) > max_val: 
     idx, max_val = idx, len(sublst) 
0

以下模式如何?

scores = [[0,0,0],[0,0],[0,0,0,0,0,0]] 
result = max(enumerate(scores), key=(lambda x: len(x[1]))) 
print(result[0]) 
print(result[1]) 
>>> 2 
>>> [0, 0, 0, 0, 0, 0]