简体   繁体   中英

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

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?

The answer given was:

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)

output:

(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"] is equivalent to:

# 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)

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

Which is equivalent to:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM