Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...