python - 使用 Python 从三维数组构建字典

标签 python python-2.7 sorting dictionary multidimensional-array

我目前在根据数组的第一列将 3D 数组数据排序到不同的字典中时遇到问题。我想检查数组的第一列,并用其中的字符串名称创建一个字典。我还想制作一个二维数组,其值位于同一行。我的数据看起来像这样:

allValues=[["str1","str1","str1","str1","str1","str1","str1","str2","str2","str2","str2","str2"],[1,2,3,4,5,6,7,8,9,10,11,12],[1,2,3,4,5,6,7,8,9,10,11,12]] 

我的目标是:

allValuesDict = {'str1': [[1,2,3,4,5,6,7], [1,2,3,4,5,6,7]], 'str2': [[8,9,10,11,12], [8,9,10,11,12]]}

最佳答案

您可以使用 collections.defaultdict 来实现 O(n) 解决方案。

请注意,这对于您当前拥有的数据结构非常具体:

from collections import defaultdict

d = defaultdict(lambda: [[], []])

for i, j, k in zip(*allValues):
    d[i][0].append(j)
    d[i][1].append(k)

如果您需要转换为常规dict:

res = dict(d)

print(res)

{'str1': [[1, 2, 3, 4, 5, 6, 7], [1, 2, 3, 4, 5, 6, 7]],
 'str2': [[8, 9, 10, 11, 12], [8, 9, 10, 11, 12]]}

关于python - 使用 Python 从三维数组构建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50222730/

相关文章:

python - 在python中查找两个列表之间的微分条件

python - Sphinx 无法处理类定义内的函数分配

Javascript 对象排序仅有时有效

Matlab求向量中重复元素的间隔

python - 在 Python 中尽快获取图像(jpg、原始文件、tiff)的高度和宽度的策略?

python - 在 Django 模板中创建排序选项

python - 如何使用 python 保持范围?

python 如何在不从列表中删除元素的情况下按出现次数对列表进行排序?

python-2.7 - RASA 没有识别出正确的 Intent

r - 通过传递带有要选择的列名的有序向量对 dplyr 中的列进行动态排序