python - 将 2D 列表转换为字典,其中重复值转换为键,其余值转换为列表

标签 python list dictionary

由于没有导入任何库来执行此操作

x=[['A',1],['B',2],['C',3]]
y=[['A',100],['B',200],['C',300]]
z=[['A',1000],['B',2000],['C',3000]]

output must:
{'A':[1,100,1000],'B':[2,200,2000],'C':[3,300,3000]}

我尝试过:

dic=dict(filter(lambda i:i[0]==i[0],[x,y,z]))

因此,作为数据,我需要首先将重复值添加到 key ,并将公共(public)值作为列表添加到该键

最佳答案

尝试:

x = [["A", 1], ["B", 2], ["C", 3]]
y = [["A", 100], ["B", 200], ["C", 300]]
z = [["A", 1000], ["B", 2000], ["C", 3000]]

out = {}
for l in (x, y, z):
    for a, b in l:
        out.setdefault(a, []).append(b)

print(out)

打印:

{"A": [1, 100, 1000], "B": [2, 200, 2000], "C": [3, 300, 3000]}

编辑:没有dict.setdefault:

x = [["A", 1], ["B", 2], ["C", 3]]
y = [["A", 100], ["B", 200], ["C", 300]]
z = [["A", 1000], ["B", 2000], ["C", 3000]]

out = {}
for l in (x, y, z):
    for a, b in l:
        if a in out:
            out[a].append(b)
        else:
            out[a] = [b]

print(out)

关于python - 将 2D 列表转换为字典,其中重复值转换为键,其余值转换为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74507106/

相关文章:

python子进程隐藏stdout并等待它完成

Python正则表达式单词、ip和端口组合匹配

python - 配置 Vim 工作区以使用多种语言进行编程?

python - 嵌套 for 循环的更多 Pythonic 方式

python - 是否可以在字典定义中结合理解和键值列表?

python - 查找文本中单词之间的关系

python - 用多个字典值替换字符串中的单词?

performance - 我可以使用 Scheme 有效地实现快速排序吗?

R:导出和导入列表到 .txt 文件

python - 有效使用Python map