假设我有两个对象列表
List1 = [{"name" : "Mac", "age":24, "id" : 1},
{"name" : "Mona","age":22, "id" : 2}]
和
List2 = [{"type" : "human","country":"AUS"}]
如何将列表2中的所有元素附加到列表1中的所有元素 这样最终的list1看起来就像
[{"name" : "Mac", "age":24, "id" : 1, "type" : "human","country":"AUS"},{"name" : "Mona", "age":22, "id" : 2, "type" : "human","country":"AUS"}]
当前正在遍历并在列表上进行更新,该列表正在运行,但是我想知道是否有更简便,更好的方法来完成此操作
for person in List1:
person.update(List2)
print List1
答案 0 :(得分:0)
List1 = [{"name" : "Mac", "age":24, "id" : 1},
{"name" : "Mona","age":22, "id" : 2}]
List2 = [{"type" : "human","country":"AUS"}]
List1 = List1 + List2
这将起作用,我已经在Python 2.7中进行了检查。希望这个答案有帮助。
答案 1 :(得分:0)
您也可以尝试以下代码-
List1 = [{"name" : "Mac", "age":24, "id" : 1},
{"name" : "Mona","age":22, "id" : 2}]
List2 = [{"type" : "human","country":"AUS"}]
finalList = [dict(l.items() + List2[0].items()) for l in List1]
print finalList