【问题标题】:Merge 2 lists and remove duplicates in Python在 Python 中合并 2 个列表并删除重复项
【发布时间】:2020-05-20 02:24:15
【问题描述】:

我有 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
      },
      ...

感谢您的帮助。

【问题讨论】:

  • 您要合并哪个列表?
  • 您想要data :{humidity:{[...]}, temperature:{[...]}}data{[...]} 之类的东西吗?
  • @GabrielAvendaño 我编辑了这个问题,明确回答了你的问题:)
  • temp_data 和 hum_data 是否有序?
  • 我刚刚遇到错误,它们是 ReturnDict,但我的调试器说它们是列表。它们是有序的

标签: python django


【解决方案1】:

如果您的列表 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}]}
    }
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-22
    • 2015-11-29
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    相关资源
    最近更新 更多