首页 > 解决方案 > 将 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() 将始终以相同的顺序返回键,这不是一个安全的假设

有没有办法避免这种情况?也许使用熊猫?

标签: pythonpandas

解决方案


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 ... }


推荐阅读