我目前在根据数组的第一列将 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/