JAK*_*AKE -2 python list pandas
我有两个这样的元组列表:
x1 = [('A', 3), ('B', 4), ('C', 5)]
x2 = [('B', 4), ('C', 5), ('D', 6)]
Run Code Online (Sandbox Code Playgroud)
我想将两个列表合并为一个新的x3,以便添加列表中的值.
x3 = [('A', 3), ('B', 8), ('C', 10),('D',6)]
Run Code Online (Sandbox Code Playgroud)
你能告诉我怎么做吗?
您可以创建一个字典,然后循环遍历每个列表中的值,并为字典中的每个键添加当前值,或者如果当前没有值,则将值设置为当前值.然后你可以回到列表.
例如:
full_dict = {}
for x in [x1, x2]:
for key, value in x:
full_dict[key] = full_dict.get(key, 0) + value # add to the current value, if none found then use 0 as current value
x3 = list(full_dict.items())
Run Code Online (Sandbox Code Playgroud)
结果x3:
[('A', 3), ('B', 8), ('C', 10), ('D', 6)]
Run Code Online (Sandbox Code Playgroud)