indices = [i for i, x in enumerate(my_list) if x == "whatever"]
相当于:
# Create an empty list
indices = []
# Step through your target list, pulling out the tuples you mention above
for index, value in enumerate(my_list):
# If the current value matches something, append the index to the list
if value == 'whatever':
indices.append(index)
结果列表包含每个匹配项的索引位置。采用相同的for
结构,您实际上可以更深入地遍历列表列表,从而使您陷入 Inception 式的疯狂螺旋:
In [1]: my_list = [['one', 'two'], ['three', 'four', 'two']]
In [2]: l = [item for inner_list in my_list for item in inner_list if item == 'two']
In [3]: l
Out[3]: ['two', 'two']
这相当于:
l = []
for inner_list in my_list:
for item in inner_list:
if item == 'two':
l.append(item)
您在开头包含的列表理解是我能想到的最 Pythonic 的方式来完成您想要的。