Python 3.x 如何获取列表中所有字符的所有索引?
我想创建一个字典,它将列表中的一个字符作为键,该值应该是一个新列表,其中包含字符所在的索引 比如: 列表=[“a”、“b”、“a”、“d”] 应该回来 {a:[0,2],“b:[0],“d:[3]} 我在写一个返回特定字符索引列表的理解时没有问题,例如“a”Python 3.x 如何获取列表中所有字符的所有索引?,python-3.x,list,dictionary,Python 3.x,List,Dictionary,我想创建一个字典,它将列表中的一个字符作为键,该值应该是一个新列表,其中包含字符所在的索引 比如: 列表=[“a”、“b”、“a”、“d”] 应该回来 {a:[0,2],“b:[0],“d:[3]} 我在写一个返回特定字符索引列表的理解时没有问题,例如“a” def idx(chars): d = {} l = [i for i,x in enumerate(chars) if x == "a"] for c in chars: d[c
def idx(chars):
d = {}
l = [i for i,x in enumerate(chars) if x == "a"]
for c in chars:
d[c] = l
return d
print(idx(["a","b","c", "a", "z", "v"]))
但是我如何将其推广到迭代所有字符并获得它们的索引呢?您可以迭代成对的
(索引,元素)
,并将索引附加到与元素对应的键上
>>> from collections import defaultdict
>>> l = ["a","b","a", "d"]
>>> res = defaultdict(list)
>>> for idx, el in enumerate(l):
... res[el].append(idx)
...
>>> res
defaultdict(<class 'list'>, {'a': [0, 2], 'b': [1], 'd': [3]})
>>从集合导入defaultdict
>>>l=[“a”、“b”、“a”、“d”]
>>>res=defaultdict(列表)
>>>对于idx,枚举中的el(l):
…res[el].追加(idx)
...
>>>res
defaultdict(,{'a':[0,2],'b':[1],'d':[3]})