[英]Find index of longest sub-list in 2D list
我最初有两个数组,一个包含数字,另一个与值相关:
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
。 请提高效率,这是我目前关注的问题 。
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
,因此我认为您无法在效率方面做得更好。
遍历总分时(idx, value)
使用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)
如何遵循模式?
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.