如何在双列表中找到最大列数的列?python

如何在双列表中找到最大列数的列?python,python,list,algorithm,Python,List,Algorithm,例如,我们有一个双重清单 lst = [[1, 0, 1, 1, 1], [1, 0, 1, 0, 0], [1, 0, 0, 0, 1]] 我需要得到列的索引,其中包含最大数量的1,因此对于本例,答案是0列。如果没有熊猫功能,请您可以执行以下操作: cols = [*zip(*lst)] # transpose the matrix # call max on the index range with appropriate key function i =

例如,我们有一个双重清单

lst = [[1, 0, 1, 1, 1],
       [1, 0, 1, 0, 0],
       [1, 0, 0, 0, 1]]

我需要得到列的索引,其中包含最大数量的
1
,因此对于本例,答案是
0列
。如果没有熊猫功能,请

您可以执行以下操作:

cols = [*zip(*lst)]   # transpose the matrix

# call max on the index range with appropriate key function
i = max(range(len(cols)), key=lambda i: sum(cols[i]))

如果存在除
0,1
以外的其他元素,
cols[i].count(1)
是更好的键函数。

首先,您需要按zip转换矩阵:

lst = [*zip(*lst)] 
通过列表理解,您可以执行以下操作:

tmp = [i.count(1) for i in lst] # in your case, tmp is [4,2,2]
ans = tmp.index(max(tmp))
关于列表理解语法:

newlist = [expression for item in iterable if condition == True]

您可以使用zip和map获取每列中的1数,然后使用max函数查找最大值的索引:

lst = [[1, 0, 1, 1, 1],
       [0, 0, 1, 1, 0],
       [1, 0, 0, 1, 1]]

_,i = max((s,i) for i,s in enumerate(map(sum,zip(*lst))))

print(i) # 3

StackOverflow不是免费的编码服务。你应该会的。请更新您的问题,以显示您已在某个应用程序中尝试过的内容。有关更多信息,请参阅,并选择:)以
max(范围(len(lst[0]))开始,key=something)
并找出
something
应该是什么