繁体   English   中英

合并 2 个列表并删除 Python 中的重复项

[英]Merge 2 lists and remove duplicates in Python

我有 2 个列表,看起来像:

临时数据:

{
  "id": 1,
  "name": "test (replaced)",
  "code": "test",
  "last_update": "2020-01-01",
  "online": false,
  "data": {
    "temperature": [
      {
        "date": "2019-12-17",
        "value": 23.652905748126333
      },
      ...
    ]}

hum_data:

{
  "id": 1,
  "name": "test (replaced)",
  "code": "test",
  "last_update": "2020-01-01",
  "online": false,
  "data": {
    "humidity": [
      {
        "date": "2019-12-17",
        "value": 23.652905748126333
      },
      ...
    ]}

我需要将 2 个列表合并为 1 个而不复制数据。 什么是最简单/有效的方法? 合并后,我想要这样的东西:

{
  "id": 1,
  "name": "test",
  "code": "test",
  "last_update": "2020-01-01",
  "online": false,
  "data": {
    "temperature": [
      {
        "date": "2019-12-17",
        "value": 23.652905748126333
      },
      ...
    ],
    "humidity": [
      {
        "date": "2019-12-17",
        "value": 23.652905748126333
      },
      ...

谢谢你的帮助。

如果您的列表 hum_data 和 temp_data 未排序,则首先对它们进行排序,然后成对地连接字典。

# To make comparisons for sorting
compare_function = lambda value : value['id']

# sort arrays before to make later concatenation easier
temp_data.sort(key=compare_function)
hum_data.sort(key=compare_function)


combined_data = temp_data.copy()

# concatenate the dictionries using the update function
for hum_row, combined_row in zip(hum_data, combined_data):
    combined_row['data'].update(hum_row['data'])

# combined hum_data and temp_data
combined_data

如果列表已经排序,那么您只需要按字典连接字典。

combined_data = temp_data.copy()

# concatenate the dictionries using the update function
for hum_row, combined_row in zip(hum_data, combined_data):
    combined_row['data'].update(hum_row['data'])

# combined hum_data and temp_data
combined_data

使用该代码,我得到了以下结果:

[
    {
    'id': 1,
    'name': 'test (replaced)',
    'code': 'test',
    'last_update': '2020-01-01',
    'online': False,
    'data': {
        'temperature': [{'date': '2019-12-17', 'value': 1}],
        'humidity': [{'date': '2019-12-17', 'value': 1}]}
    },
    {
    'id': 2,
    'name': 'test (replaced)',
    'code': 'test',
    'last_update': '2020-01-01',
    'online': False,
    'data': {
        'temperature': [{'date': '2019-12-17', 'value': 2}],
        'humidity': [{'date': '2019-12-17', 'value': 2}]}
    }
]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM