如何查找列表中所有出现的元素? [英] How to find all occurrences of an element in a list?

查看:77
本文介绍了如何查找列表中所有出现的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I read the post: How to find all occurrences of an element in a list? How to find all occurrences of an element in a list?

给出的答案是:

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

我知道这是列表理解,但我无法破解这段代码并理解它。有人可以请给我吃饭吗?

I know this is list comprehension but I cannot break this code down and understand it. Can someone please piece meal it for me?

如果执行以下代码:我知道枚举只会创建一个元组:

If do the following code:I know enumerate will just create a tuple:

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

输出:

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

如果有一种更简单的方法,我也会对此持开放态度。

If there's a simpler way I'd be open to that too.

推荐答案

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)

结果列表包含每个匹配的索引位置。对于构造采用相同的,您实际上可以更深入地遍历列表列表,将您发送到一个由Inception-esque螺旋形的疯狂:

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']

这相当于:

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.

这篇关于如何查找列表中所有出现的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆