Python 如何在列表中查找元素的所有引用?

Python 如何在列表中查找元素的所有引用?,python,list,indexing,element,Python,List,Indexing,Element,我读了这篇文章:如何在列表中找到元素的所有匹配项? 答案是: indices = [i for i, x in enumerate(my_list) if x == "whatever"] 我知道这是列表理解,但我不能分解这个代码并理解它。有人能帮我把它切成小块吗 如果执行以下代码:我知道enumerate将只创建一个元组: l=['a','b','c','d'] enumerate(l) 输出: (0, 'a') (1, 'b') (2, 'c') (3, 'd') 如果有更简单的方

我读了这篇文章:如何在列表中找到元素的所有匹配项?

答案是:

indices = [i for i, x in enumerate(my_list) if x == "whatever"]
我知道这是列表理解,但我不能分解这个代码并理解它。有人能帮我把它切成小块吗


如果执行以下代码:我知道enumerate将只创建一个元组:

l=['a','b','c','d']
enumerate(l)
输出:

(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')

如果有更简单的方法,我也会接受的

索引=[i代表i,如果x==“whatever”]
相当于:

indices = []
for idx, elem in enumerate(my_list):
    if elem=='whatever':
        indices.append(idx)
# 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)
l = []
for inner_list in my_list:
  for item in inner_list:
    if item == 'two':
      l.append(item)
结果列表包含每个匹配的索引位置。对于构造,使用相同的
,您实际上可以更深入地遍历列表列表,将您送入一个类似于《盗梦空间》的疯狂螺旋:

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']
这相当于:

# 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)
l = []
for inner_list in my_list:
  for item in inner_list:
    if item == 'two':
      l.append(item)

你在开始时所包含的列表理解是我能想到的实现你想要的东西的最简单的方式。

列表理解中没有火箭科学@用户1527227完全没有问题,很乐意帮助!我建议练习列表理解,直到它们开始“点击”——它们是你开始掌握的功能之一,然后你想知道没有它们你怎么能活下去:)这是我找到的最好的解释之一。