[英]How to find index of item with shortest list inside?
So I have a list in this format: 所以我有一个这种格式的列表:
lst = [[x1, y1, [1,3,4]], [x2, y2, [6,3]], [x3, y3, [8,6,3,9]]]
I want to find the index of item with the shortest list inside . 我想找到里面有最短列表的项目索引。 ie In this case it would return
[x2, y2, [6,3]]
since [6,3]
is the shortest list in this case. 即在这种情况下,它将返回
[x2, y2, [6,3]]
因为[6,3]
是这种情况下的最短列表。
Of course I can iterate through to find the shortest item but is there better/faster way to do this in python? 当然我可以迭代找到最短的项目,但有更好/更快的方式在python中执行此操作?
Use the min
, providing a key function that returns the length of the sublist: 使用
min
,提供一个返回子列表长度的键函数:
min(lst, key=lambda item: len(item[2]))
Note that iteration over lst
still takes place implicitly when using min
. 注意,当使用
min
时,仍然会隐式地进行lst
上的迭代。 There is no other way to check every item than to iterate. 除了迭代之外,没有其他方法可以检查每个项目。
If you really need the index do: 如果您确实需要索引,请执行以下操作:
index = min(range(len(lst)), key=lambda dx: len(lst[dx][2])
In [33]: lst = [['x1', 'y1', [1,3,4]], ['x2', 'y2', [6,3]], ['x3', 'y3', [8,6,3,9]]]
In [34]: min(enumerate(lst), key=lambda t : min(len(s) for s in t[1] if isinstance(s,list)))[0]
Out[34]: 1
确实,有:
min(lst, key=lambda x: len(x[-1]))
If inner list is always the last one item 如果内部列表始终是最后一个项目
from itertools import imap
your_min = min(imap(len, (item[-1] for item in your_list)))
or if you want index: 或者如果你想要索引:
def find_index(lst):
min_len = 1e10
min_idx = None
for i, v in enumerate(your_list):
curr_len = len(v[-1])
if curr_len < min_len:
min_len = curr_len
min_idx = i
return i
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.