python - 有没有一种更简单快捷的方法来获取索引字典,其中包含列表或 numpy 数组中相同元素的索引

标签 python arrays numpy indexing

描述:

我有一个大数组,其中包含简单的整数(正数且不大),例如 1、2、... 等。例如:[1、1、2、2、1、2]。我想得到一个字典,其中使用列表中的单个值作为字典的键,并将该值的索引列表用作字典的值。

问题:

有没有更简单快捷的方法在python中得到预期的结果? (数组可以是列表或 numpy 数组)

代码:

a = [1, 1, 2, 2, 1, 2]
results = indexes_of_same_elements(a)
print(results)

预期结果:

{1:[0, 1, 4], 2:[2, 3, 5]}

最佳答案

您可以在这里使用矢量化方法避免迭代,特别是 np.unique + np.argsort:

idx = np.argsort(a)
el, c = np.unique(a, return_counts=True)

out = dict(zip(el, np.split(idx, c.cumsum()[:-1])))

{1: array([0, 1, 4], dtype=int64), 2: array([2, 3, 5], dtype=int64)} 

性能

a = np.random.randint(1, 100, 10000)

In [183]: %%timeit
     ...: idx = np.argsort(a)
     ...: el, c = np.unique(a, return_counts=True)
     ...: dict(zip(el, np.split(idx, c.cumsum()[:-1])))
     ...:
897 µs ± 41.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [184]: %%timeit
     ...: results = {}
     ...: for i, k in enumerate(a):
     ...:     results.setdefault(k, []).append(i)
     ...:
2.61 ms ± 18.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

关于python - 有没有一种更简单快捷的方法来获取索引字典,其中包含列表或 numpy 数组中相同元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53000907/

相关文章:

python - 如何用键初始化defaultdict?

Python 3.2 被动用户输入

python - Windows 中的另一个 GDAL 导入错误

android - 使用 buildozer 使用适用于 Android 的 numpy 库打包 Kivy 时出错

python - 将 CNN 过滤器权重可视化为 tensorflow 中的 numpy 数组

python - django slugify - 定制德语变音符号

javascript - 将字符串更改为双引号

javascript - 使用 jQuery 从 JSON 树读取特定值

c - 使用结构的邮政编码

python - 对 3D 空间中的所有点进行叉积