簡體   English   中英

如何查找列表中所有出現的元素?

[英]How to find all occurrences of an element in a list?

我讀了帖子:如何查找列表中所有出現的元素? 如何查找列表中所有出現的元素?

答案是:

indices = [i for i, x in enumerate(my_list) if x == "whatever"]

我知道這是列表理解,但我無法破解這些代碼並理解它。 有人可以請我吃飯嗎?


如果執行以下代碼:我知道枚舉將只創建一個元組:

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"]相當於:

# 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構造采用相同for ,你可以更深入地遍歷列表列表,將你帶入一個以神奇為中心的瘋狂:

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)

你在開始時包含的列表理解是我能想到的最恐怖的方式來實現你想要的。

indices = []
for idx, elem in enumerate(my_list):
    if elem=='whatever':
        indices.append(idx)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM