python - 如何在 Python 中构建列表中元素出现索引的字典?

标签 python numpy

将列表中所有元素出现的索引转换为字典的最快方法是什么?

例如:

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/

相关文章:

c# - 如何导出 C# 方法?

python - 用 Pandas 计算矩阵的逆

python - 使用 .loc 查询非空值和仅字符串值

python - f2py -- 防止数组重新排序

python - Pandas - 如何将重复方法的结果存储为新列中的 bool 值?

python - 从在 python 中创建的包含新操作的 pb 图在 c++ 中创建图

numpy - 确定哪个编译器构建了我的 LAPACK

python - 将数据从一个 Numpy 数组移动到另一个返回错误数据

python - 如何使用 numpy 将 alpha channel (透明度)添加到背景(不是正面图像)

python numpy left join rearray 具有重复的键值