如何根据条件从列表中获取元素及其索引?
How can I get both elements and their indices from a list based on a condition?
我有一个包含重复值的列表,我找到了最大长度的列表,但我想获取这些最大列表的索引并将它们添加到我的索引列表中。
mylist = [{'destination', 'graph'}, {'vertex'}, {'destination', 'modify'}, {'destination', 'modify'}, {'modify', 'return'}, {'destination'}]
max_len = len(sorted(mylist, key=lambda x: len(x), reverse=True)[0])
uniq_list = [k for k in mylist if len(k) == max_len]
print(uniq_list)
当前输出:
[{'destination', 'graph'}, {'destination', 'modify'}, {'destination', 'modify'}, {'modify', 'return'}]
预期输出:
[{'destination', 'graph'}, {'destination', 'modify'}, {'destination', 'modify'}, {'modify', 'return'}]
index_list = [0,2,3,4]
使用enumerate
to keep both the sublists and index in tuples, and unpack them with zip
:
out = ((ix, k) for ix, k in enumerate(mylist) if len(k) == max_len)
index_list , uniq_list = zip(*out)
print(index_list)
# (0, 2, 3, 4)
print(uniq_list)
#({'graph', 'destination'}, {'modify', 'destination'},
# {'modify', 'destination'}, {'modify', 'return'})
我有一个包含重复值的列表,我找到了最大长度的列表,但我想获取这些最大列表的索引并将它们添加到我的索引列表中。
mylist = [{'destination', 'graph'}, {'vertex'}, {'destination', 'modify'}, {'destination', 'modify'}, {'modify', 'return'}, {'destination'}]
max_len = len(sorted(mylist, key=lambda x: len(x), reverse=True)[0])
uniq_list = [k for k in mylist if len(k) == max_len]
print(uniq_list)
当前输出:
[{'destination', 'graph'}, {'destination', 'modify'}, {'destination', 'modify'}, {'modify', 'return'}]
预期输出:
[{'destination', 'graph'}, {'destination', 'modify'}, {'destination', 'modify'}, {'modify', 'return'}]
index_list = [0,2,3,4]
使用enumerate
to keep both the sublists and index in tuples, and unpack them with zip
:
out = ((ix, k) for ix, k in enumerate(mylist) if len(k) == max_len)
index_list , uniq_list = zip(*out)
print(index_list)
# (0, 2, 3, 4)
print(uniq_list)
#({'graph', 'destination'}, {'modify', 'destination'},
# {'modify', 'destination'}, {'modify', 'return'})