Ver*_*tas 0 python idioms list
我有一个列表,其中包含其他列表,我想检索具有最少元素的列表.一个明显的解决方案是
list_of_list = ...
least = list_of_lists[0]
for list in list_of_lists[1:]
if len(list) < len(least):
least = list
return least
Run Code Online (Sandbox Code Playgroud)
有没有比较惯用的方法呢?
min(list_of_lists, key=len)
Run Code Online (Sandbox Code Playgroud)
这将返回最短的列表:
>>> import random
>>> list_of_lists = [[None] * random.randint(3, 10) for _ in range(10)]
>>> min(list_of_lists, key=len)
[None, None, None]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43 次 |
| 最近记录: |