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


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


汪汪一只猫
浏览 249回答 3
3回答

慕雪6442864

from numpy import transposea1 = ["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 ... }

12345678_0001

使用map, split, numpy 数组转置zip和dictn = np.array(list(map(lambda x: x.split(','), a2))).T.tolist()Out[245]: [['1', '2', '3'], ['20', '10', '40'], ['300', '300', '300']]result = dict(zip(a1, n))Out[247]: {'a': ['1', '2', '3'], 'b': ['20', '10', '40'], 'c': ['300', '300', '300']}

慕标琳琳

a1 = ["a", "b", "c"]a2 = ["1,20,300", "2,10,300", "3,40,300"]a2 = [item.split(',') for item in a2]res = {}for i in range(len(a1)):    res[a1[i]] = [item[i] for item in a2]res{'a': ['1', '2', '3'], 'b': ['20', '10', '40'], 'c': ['300', '300', '300']}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python