gpt4 book ai didi

python - 如何查找列表中元素的所有出现?

转载 作者:行者123 更新时间:2023-11-28 20:49:56 24 4
gpt4 key购买 nike

我读了这篇文章:如何查找列表中某个元素的所有出现位置? 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 结构,您实际上可以更深入地迭代列表的列表,将您送入 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 方式。

关于python - 如何查找列表中元素的所有出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13478974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com