【问题标题】:How to merge multi array of object in python?如何在python中合并多个对象数组?
【发布时间】:2021-10-13 02:40:34
【问题描述】:

我有两个数组列表,我不知道如何在 python 中合并多个对象数组?

[{'name': 'James'}, {'name': 'Abhinay'}, {'name': 'Peter'}]

[{'age': 1}, {'age': 2}, {'age': 3}]

我想要什么

[{'name': 'James','age':1}, {'name': 'Abhinay','age':2}, {'name': 'Peter','age':3}]

【问题讨论】:

  • 您已将此标记为 Python 2.7 和 3.X,这需要哪个版本?
  • 可能的解决方案有很大不同,具体取决于您想要 python2.7 还是 3.x。你在标记什么?
  • @BTables 我修好了
  • @IainShelvington 我修好了

标签: python python-3.x list dictionary


【解决方案1】:

这是一种可行的方法:

L1 = [{'name': 'James'}, {'name': 'Abhinay'}, {'name': 'Peter'}]
L2 = [{'age': 1}, {'age': 2}, {'age': 3}]

result = [dict(**x, **y) for x, y in zip(L1, L2)]

print(result)
# [{'name': 'James', 'age': 1}, {'name': 'Abhinay', 'age': 2}, {'name': 'Peter', 'age': 3}]

在 Python 3.9 或更高版本中使用 dict union | 运算符:

result = [x | y for x, y in zip(L1, L2)]

【讨论】:

  • 谢谢,但是如果我有两个以上的数组怎么办?
  • 我收到了这个错误:“TypeError: 'NoneType' 类型的属性不可调用”
  • @user12217822 该模式是可扩展的,对于 3 个列表,您将使用 [x | y | z for x, y, z in zip(L1, L2, L3)]
  • @user12217822 给定的代码可以完美运行并产生所需的输出。
  • @user12217822 您可能已经覆盖了dictzip 内置名称
猜你喜欢
  • 1970-01-01
  • 2016-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-20
  • 2017-11-10
  • 2022-11-08
相关资源
最近更新 更多