查找多个列表的最小长度

时间:2022-08-22 13:03:49

I have three lists of different lengths.

我有三个不同长度的列表。

For example

例如

List1 is of length 40
List2 is of length 42
List3 is of length 47

How can I use the Python inbuilt min() or any other method to find the list with the minimum length?

如何使用Python内置的min()或任何其他方法来查找具有最小长度的列表?

I tried:

我试过了:

 min(len([List1,List2,List3]))

but I get TypeError: 'int' object is not iterable

但我得到TypeError:'int'对象不可迭代

2 个解决方案

#1


11  

You need to apply len() to each list separately:

您需要分别对每个列表应用len():

shortest_length = min(len(List1), len(List2), len(List3))

If you already have a sequence of the lists, you could use the map() function or a generator expression:

如果您已经有一系列列表,则可以使用map()函数或生成器表达式:

list_of_lists = [List1, List2, List3]
shortest_length = min(map(len, list_of_lists))  # map function
shortest_length = min(len(l) for l in list_of_lists)  # generator expr

To find the shortest list, not the shortest length, use the key argument:

要查找最短列表,而不是最短的长度,请使用key参数:

list_of_lists = [List1, List2, List3]
shortest_list = min(list_of_lists, key=len)

#2


3  

Use generator expression

使用生成器表达式

min(len(i) for i in [List1,List2,List3])

#1


11  

You need to apply len() to each list separately:

您需要分别对每个列表应用len():

shortest_length = min(len(List1), len(List2), len(List3))

If you already have a sequence of the lists, you could use the map() function or a generator expression:

如果您已经有一系列列表,则可以使用map()函数或生成器表达式:

list_of_lists = [List1, List2, List3]
shortest_length = min(map(len, list_of_lists))  # map function
shortest_length = min(len(l) for l in list_of_lists)  # generator expr

To find the shortest list, not the shortest length, use the key argument:

要查找最短列表,而不是最短的长度,请使用key参数:

list_of_lists = [List1, List2, List3]
shortest_list = min(list_of_lists, key=len)

#2


3  

Use generator expression

使用生成器表达式

min(len(i) for i in [List1,List2,List3])