Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何获取列表中所有字符的所有索引?_Python 3.x_List_Dictionary - Fatal编程技术网

Python 3.x 如何获取列表中所有字符的所有索引?

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

我想创建一个字典,它将列表中的一个字符作为键,该值应该是一个新列表,其中包含字符所在的索引

比如: 列表=[“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] = 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]})