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

编程入门 行业动态 更新时间:2024-10-25 10:27:05
本文介绍了如何查找列表中所有出现的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

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

本文发布于:2023-11-29 23:32:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647965.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!