合并列表中的数据
如何合并列表以获得所需的效果?考虑以下两个列表:
book1 = [{ "高校": ["南京大学", "天津大学", "南开大学"] }, { "国家": ["印度", "美国"] }] book2 = [{ "高校": ["南京大学", "东华大学", "中南大学"] }, { "国家": ["乌克兰", "俄罗斯"] }, { "论坛": ["顶尖科学家论坛", "统计之都"] }]
目标是将这些列表合并成以下结构:
book3 = [{ "高校": ["南京大学", "天津大学", "南开大学", "东华大学", "中南大学"] }, { "国家": ["印度", "美国", "乌克兰", "俄罗斯"] }, { "论坛": ["顶尖科学家论坛", "统计之都"] }]
合并过程
合并过程中需要考虑以下几点:
以下代码演示了合并过程:
gx = [] gj = [] lt = [] for i in book1[0]["高校"]: gx.append(i) for i in book1[1]["国家"]: gj.append(i) for i in book2[0]["高校"]: if gx.count(i) == 0: gx.append(i) for i in book2[1]["国家"]: if gj.count(i) == 0: gj.append(i) for i in book2[2]["论坛"]: lt.append(i) newbook3 = [{ "高校": gx }, { "国家": gj }, { "论坛": lt }]
动态遍历
上面的代码适用于列表结构稳定的情况。如果列表结构不稳定,需要动态遍历键名:
newOBJ = {} newBook = [] def appendList(aList): for i in range(len(aList)): for k, v in aList[i].items(): if k in newOBJ: CList = newOBJ[k] else: newOBJ[k] = [] CList = newOBJ[k] for z in v: if CList.count(z) == 0: CList.append(z) appendList(book1) appendList(book2) for k, v in newOBJ.items(): newBook.append({k: v})