简体   繁体   English

如何获取唯一值的索引列表?

[英]How to get list of indexes for unique values?

Having a list like this有这样的清单

lst = ['a','b','a','c','a','b','b']

I'd like to get lists of indexes for each unique element to get this:我想获取每个唯一元素的索引列表以获取此信息:

indexes = {
            'a': [0,2,4],
            'b': [1,5,6],
            'c': [3]
          }

This is my current code, but I'm only getting the first index of each element.这是我当前的代码,但我只获取每个元素的第一个索引。

indexes= dict()
for el in lst:
    indexes[el] = [lst.index(el)]

>>> indexes
{'a': [0], 'b': [1], 'c': [3]}

Thanks for any help.谢谢你的帮助。

The problem with you code is you're overriding the same key again and again but with a different list , so your final dictionary contains only a single list .您的代码的问题是您一次又一次地覆盖相同的键,但使用不同的list ,因此您的最终字典仅包含一个list

you can avoid this behavior by using defaultdict .您可以通过使用defaultdict来避免这种行为。

from collections import defaultdict

lst = ["a", "b", "a", "c", "a", "b", "b"]
lst = [c for c in lst if c.strip()]  # this will remove empty strings

indexes = defaultdict(list)

for index, char in enumerate(lst):
    indexes[char].append(index)

indexes = dict(indexes)
print(indexes)

Output: Output:

{'a': [0, 2, 4], 'b': [1, 5, 6], 'c': [3]}

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

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