indices = [i for i, x in enumerate(my_list) if x == "whatever"]
is equivalent to:
# 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)
The resulting list contains the index positions of each match. Taking that same for
construct, you can actually go deeper and iterate through lists-of-lists, sending you into an Inception-esque spiral of madness:
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']
Which is equivalent to:
l = []
for inner_list in my_list:
for item in inner_list:
if item == 'two':
l.append(item)
The list comprehension you include at the beginning is the most Pythonic way I can think of to accomplish what you want.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…