我有2个列表,其中包含以下数据结构:
array1:
[{'student': {'name': 'abc'}, 'address': 'add_abc'},
{'student': {'name': 'xyz'}, 'address': 'add_xyz'}]
array2:
[{'student': {'name': 'abc'}, 'address': 'add_abc'},
{'student': {'name': 'rst'}, 'address': 'add_rst'}]
我希望array3
拥有以上2个列表的联合
array3:
[{'student': {'name': 'abc'}, 'address': 'add_abc'},
{'student': {'name': 'rst'}, 'address': 'add_rst'},
{'student': {'name': 'xyz'}, 'address': 'add_xyz'}]
我怎么能用Python做到这一点?
答案 0 :(得分:5)
它们是lists
,而不是数组,但这是一个解决方案:
a1 = [{'student': {'name': 'abc'}, 'address': 'add_abc'},
{'student': {'name': 'xyz'}, 'address': 'add_xyz'}]
a2 = [{'student': {'name': 'abc'}, 'address': 'add_abc'},
{'student': {'name': 'rst'}, 'address': 'add_rst'}]
a3 = a1 + [i for i in a2 if i not in a1]
a3
的值将为
[{'student': {'name': 'abc'}, 'address': 'add_abc'},
{'student': {'name': 'xyz'}, 'address': 'add_xyz'},
{'student': {'name': 'rst'}, 'address': 'add_rst'}]
如果您希望对结果列表进行排序(例如,按学生姓名),只需使用sort
方法:
a3.sort(key=lambda x: x["student"]["name"])
,结果a3
将是:
[{'student': {'name': 'abc'}, 'address': 'add_abc'},
{'student': {'name': 'rst'}, 'address': 'add_rst'},
{'student': {'name': 'xyz'}, 'address': 'add_xyz'}]
通常情况下,您只需使用set(a1 + a2)
,但问题是您dict
内有list
个且它们不可用,因此无法设置项目。