python - 将 2 个数组组合成一个字典
问题描述
我有一个字符串数组(a1
):["a", "b", "c"]
另一个 ( a2
) 看起来像这样:
["1,20,300", "2,10,300", "3,40,300", "1, 20, 300, 4000"]
想要的最终结果是:
{"a": [1,2,3,1], "b": [20, 10, 40, 20], "c": [300, 300, 300, 4000] }
可以安全地假设它a2[n].split(',')
总是以正确的顺序给我项目,即 的顺序["a", "b", "c"]
,就像在示例中一样。
考虑到这一点,是否可以不必循环两次和/或不必假设字典中键的顺序是一致的?
我的解决方案是:
a1 = ["a", "b", "c"]
a2 = ["1,20,300", "2,10,300", "3,40,300"]
result = {}
for i in a1:
result[i] = []
for e in a2:
splitted = e.split(",")
c = 0
for key,array in result.items():
result[key].append(splitted[c])
c = c+1
这需要许多循环并假设 result.items() 将始终以相同的顺序返回键,这不是一个安全的假设。
有没有办法避免这种情况?也许使用熊猫?
解决方案
from numpy import transpose
a1 = ["a", "b", "c"]
a2 = ["1,20,300", "2,10,300", "3,40,300"]
a2t = transpose([e.split(",") for e in a2])
result = {a1[i] : list(a2t[i]) for i in range(len(a1))}
=> {'a': ['1', '2', '3'], 'b': ['20', '10', '40'], 'c': ['300', '300', '300']}
感谢 Code-Apprentice 建议使用 {x : y for ... }
推荐阅读
- orbeon - Orbeon 表单中的批量更新权限
- c# - 如何使两个数组中的元素成为条件,Linq c#
- mp4 - AAC 音频文件播放速度比正常速度快
- html - 如何使我的网站具有响应性 - 表格文本相互重叠
- java - 如何重写 document.getElementsByTagName(); 与 XPath?
- javascript - 如何修复我的项目中未加载图像和 CSS 的问题?
- php - Cakephp 3.6.14:创建带有复选框和处理数据的表格
- xml - XSLT 代码仅获取最新日期的 XML 记录
- javascript - C3/D3 饼图图例格式/标签重叠
- visual-studio-code - vscode tasks.json中的process和shell有什么区别