Python:如何查找其中包含最多元素的列表

时间:2019-02-21 12:04:47

标签: python-3.x

使用Python,我想输出列表中包含最多元素的名称。

List1 [1,2,4,5,7,2]
List2 [1,4,5,6]
List3 [2,5,4,6,7,8,5,3,]

2 个答案:

答案 0 :(得分:0)

您可以将列表组合成一个列表字典,然后如前所述,对(列表的)字典值内的每个元素运行len函数以检查长度,然后使用max,如果长度与值匹配,则返回键。

它还会告诉您列表的长度是否相同:

list1 = [1,2,4,5,7,6,5]
list2 = [1,4,5,6]
list3 = [2,5,4,6,7,8,5,3]

list_dict = {}
list_dict['list1'] = list1
list_dict['list2'] = list2
list_dict['list3'] = list3

lengths = {key: len(x) for key, x in list_dict.items()}
longest = max(lengths.values())

for k, v in lengths.items():
  if v == longest:
    print(f'{k} is the longest list')



>>> list3 is the longest list

答案 1 :(得分:0)

您可以使用numpy:

import numpy as np

list1 = [1,2,4,5,7,6,5]
list2 = [1,4,5,6]
list3 = [2,5,4,6,7,8,5,3]

lists=[list1, list2, list3]
listsnames=["list1", "list2", "list3"]

most= listsnames[np.argmax([len(l) for l in lists])]