//python 一个单列表和一个字典元素的列表合并,组成一个新列表:
# by coco
# 20160106
举例:
a = [1,2,3,4]
b=[{"no":1,"name":"tom","sex":"M"},{"no":3,"name":"lily","sex":"F"}]
组合后的新列表为:
c =[{'sex': 'M', 'name': 'tom', 'no': 1}, {'sex': 0, 'name': 0, 'no': '2'}, {'sex': 'F', 'name': 'lily', 'no': 3}, {'sex': 0, 'name': 0, 'no': '4'}]
代码如下:
a = ['1','2','3','4'] b=[{"no":1,"name":"tom","sex":"M"},{"no":3,"name":"lily","sex":"F"}] def expand_list_1(b,a): expand_list_1,tmp_list=[],[] tmp_list=dict([(i,{"no":i,"name":0,"sex":0}) for i in a]) for j in b: tmp_list[str(j["no"])]=j expand_list_1=sorted(tmp_list.values(),key=lambda j:str(j["no"])) return expand_list_1 bb = expand_list_1(b,a) print bb
例子2:
一个时间列表:
datelist=['20151206', '20151207', '20151208', '20151209', '20151210', '20151211', '20151212', '20151213', '20151214']
一个字典元素的列表:
dictinfo=[{'dateinfo': 20151206L, 'release_count': '1076', 'online_count': '8279'}, {'dateinfo': 20151210L, 'release_count': '4024', 'online_count': '8279'}, {'dateinfo': 20151212L, 'release_count': '3267', 'online_count': '8279'}]
安装日期列表组合新列表,要求:具体到日期当天有值的,为当天对应的值,否则 字典元素补0
组合后新列表:
new_list = [{'dateinfo': 20151206L, 'release_count': '1076', 'online_count': '8279'}, {'dateinfo': '20151207', 'release_count': 0, 'online_count': 0}, {'dateinfo': '20151208', 'release_count': 0, 'online_count': 0}, {'dateinfo': '20151209', 'release_count': 0, 'online_count': 0}, {'dateinfo': 20151210L, 'release_count': '4024', 'online_count': '8279'}, {'dateinfo': '20151211', 'release_count': 0, 'online_count': 0}, {'dateinfo': 20151212L, 'release_count': '3267', 'online_count': '8279'}, {'dateinfo': '20151213', 'release_count': 0, 'online_count': 0}, {'dateinfo': '20151214', 'release_count': 0, 'online_count': 0}]
代码如下:
# test 2 print "test 2...." datelist=['20151206','20151207','20151208','20151209','20151210','20151211','20151212','20151213','20151214'] dictinfo=[{'dateinfo': 20151206L,'release_count': '1076','online_count':'8279'},{'dateinfo': 20151210L,'release_count': '4024','online_count':'8279'},{'dateinfo': 20151212L,'release_count':'3267','online_count':'8279'}] print datelist print dictinfo # 列表中元素根据日期:有的为其值,没有的话 补0 封装成一个公共函数。 def expand_list(dictinfo,datelist): ''' dictinfo : 字典列表 elementlist : [20150101,20150102] ''' expand_list,tmp_list=[],[] tmp_list=dict([(i,{"dateinfo":i,"release_count":0,"online_count":0}) for i in datelist]) for j in dictinfo: tmp_list[str(j["dateinfo"])]=j expand_list=sorted(tmp_list.values(),key=lambda j:str(j["dateinfo"])) return expand_list a=expand_list(dictinfo,datelist)