As No import any library To Do This
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]}
I tried:
dic=dict(filter(lambda i:i[0]==i[0],[x,y,z]))
So As Data我首先需要复制值到键,并将此键的公共值作为列表
尝试:
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]}
EDIT: Withoutdict.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)
您可以使用zip
将列表合并为元组列表,并将它们插入setdefault
dict
中。d = dict()
for k, v in zip(*zip(*x, *y, *z)):
d.setdefault(k, []).append(v)
print(d) # {'A': [1, 100, 1000], 'B': [2, 200, 2000], 'C': [3, 300, 3000]}
让我们使用字典推导式:
dic_={x[0]: [x[1], y[1],z[1]] for (x,y,z) in zip(x, y,z)}
>>> dic
>>> {'A': [1, 100, 1000], 'B': [2, 200, 2000], 'C': [3, 300, 3000]}