将列表中所有元素出现的索引转换为字典的最快方法是什么?
例如:
A = [ 1, 2, 3, 4 , 2, 1 ]
我想 build :
B['1'] = [0, 5]
B['2'] = [1, 4]
B['3'] = [2]
B['4'] = [3]
这是为了避免调用 np.where在一个循环中多次,这对于大 A 来说太慢了。理想情况下,只想遍历数组 A 一次。 例如,要避免:
uniqA = np.unique(A)
for i in uniqA:
B[str(i)] = np.argwhere(i==A)
最佳答案
你只能迭代一次:
>>> from collections import defaultdict
>>> A = [ 1, 2, 3, 4 , 2, 1 ]
>>> d = defaultdict(list)
>>> for i,x in enumerate(A):
... d[x].append(i)
...
>>> d
defaultdict(<type 'list'>, {1: [0, 5], 2: [1, 4], 3: [2], 4: [3]})
关于python - 如何在 Python 中构建列表中元素出现索引的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22803125/