// python 两个列表合并
# by coco
# 20151231
需求是这样的:我有2个列表 ,其中列表中有一个公共key, 我想按照最长的 公共key 合并这2个列表,没有值的 补0 。如下例子:
a = [{"dateinfo":"20151220","pro_num":"100"}]
b= [{"dateinfo":"20151220","sep_num":"200"},{"dateinfo":"20151221","sep_num":"300"},{"dateinfo":"20151222","sep_num":"300"}]
最终我想要的合并列表结果如下:
c= [{"dateinfo":"20151220","sep_num":"200","pro_num":"100"},{"dateinfo":"20151221","sep_num":"300","pro_num":"0"},{"dateinfo":"20151222","sep_num":"300","pro_num":"0"}]
代码如下:
a = [{"dateinfo":"20151220","pro_num":"100"}]
{"20151220":"100"}
b= [{"dateinfo":"20151220","sep_num":"200"},{"dateinfo":"20151221","sep_num":"300"},{"dateinfo":"20151222","sep_num":"300"}]
#最终我想要的合并列表结果如下:
#c= [{"dateinfo":"20151220","sep_num":"200","pro_num":"100"},{"dateinfo":"20151221","sep_num":"300","pro_num":"0"},{"dateinfo":"20151222","sep_num":"300","pro_num":"0"}]
#print a ,b
key_list = []
new_a = []
c = []
for i in b:
dateinfo = i["dateinfo"]
key_list.append(dateinfo)
print key_list
#想把a列表补齐 公共key 缺失的项目:
new_a=[({"dateinfo":i,"pro_num":0 if i not in dict([ j.values() for j in a ]).keys() else dict([ j.values() for j in a ])[i] }) for i in key_list]
print new_a
#合并 new_a,b列表,组合成所需要的新列表c
c = [dict(i,**j) for i,j in zip (new_a,b)]
print c
结果如下:
/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/coco/PycharmProjects/pyscript/py_test.py
['20151220', '20151221', '20151222']
[{'dateinfo': '20151220', 'pro_num': '100'}, {'dateinfo': '20151221', 'pro_num': 0}, {'dateinfo': '20151222', 'pro_num': 0}]
[{'dateinfo': '20151220', 'sep_num': '200', 'pro_num': '100'}, {'dateinfo': '20151221', 'sep_num': '300', 'pro_num': 0}, {'dateinfo': '20151222', 'sep_num': '300', 'pro_num': 0}]
Process finished with exit code 0