简体   繁体   English

列表中重复项的python列表索引

[英]python list indices of repeated item in list

If you have a list with repeated elements, as below, how do you get the indices for each occurrence of that element?如果您有一个包含重复元素的列表,如下所示,您如何获得该元素每次出现的索引?

Here's my example.这是我的例子。

''' '''

listy = ["apples", "oranges", "apples", "bananas", "apples", "bananas"]

print (listy.index("bananas"))

''' '''

You can see it only will yield one result - 3, which is correct, but it is only one of the banana elements in the list.你可以看到它只会产生一个结果 - 3,这是正确的,但它只是列表中的香蕉元素之一。

What if you wanted to find the indices of all the others for any of the elements?如果您想找到任何元素的所有其他元素的索引怎么办? Is there a way to do it?有没有办法做到这一点?

If your list keeps changing you can make a function which checks the index at the instant you require.如果您的列表不断变化,您可以创建一个在您需要的瞬间检查索引的函数。

find_instance = lambda ele,lst : [i for i,j in enumerate(lst) if j==ele]
# To get indexes
find_instance('bananas', listy)

If your list is static, you can use defaultdict to store the index and get your index from it.如果您的列表是静态的,您可以使用defaultdict来存储索引并从中获取索引。 It will be faster because it wont iterate the list everytime you require index.它会更快,因为它不会在每次需要索引时迭代列表。

from collections import defaultdict
my_indexes = defaultdict(list)
for i, j in enumerate(listy):
    my_indexes[j].append(i)
# To get indexes
print(my_indexes['bananas'])

As an academic exercise:作为学术练习:

listy = ["apples", "oranges", "apples", "bananas", "apples", "bananas"]

d = {k:[] for k in set(listy)}
for i,e in enumerate(listy):
   d[e].append(i)

print(d)

print('bananas', d['bananas'])

Output输出

{'oranges': [1], 'bananas': [3, 5], 'apples': [0, 2, 4]}
bananas [3, 5]

All good answers.所有的好答案。 Thank you!谢谢!

I knew it wasn't a hard question, but still got stuck on it.我知道这不是一个很难的问题,但还是被困在了这个问题上。

Sometimes it is nice just to have a bit more to think about to jar one's thinking.有时,多思考一点来扰乱自己的想法是件好事。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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