![](/img/trans.png)
[英]Most efficient way to find the indexes of unique values in a Python 3 list
[英]How to get list of indexes for unique values?
有這樣的清單
lst = ['a','b','a','c','a','b','b']
我想獲取每個唯一元素的索引列表以獲取此信息:
indexes = {
'a': [0,2,4],
'b': [1,5,6],
'c': [3]
}
這是我當前的代碼,但我只獲取每個元素的第一個索引。
indexes= dict()
for el in lst:
indexes[el] = [lst.index(el)]
>>> indexes
{'a': [0], 'b': [1], 'c': [3]}
謝謝你的幫助。
您的代碼的問題是您一次又一次地覆蓋相同的鍵,但使用不同的list
,因此您的最終字典僅包含一個list
。
您可以通過使用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:
{'a': [0, 2, 4], 'b': [1, 5, 6], 'c': [3]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.