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.
Of course I can iterate through to find the shortest item but is there better/faster way to do this in python?
Use the min
, providing a key function that returns the length of the sublist:
min(lst, key=lambda item: len(item[2]))
Note that iteration over lst
still takes place implicitly when using min
. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.