【问题标题】:Compare two lists with different objects and create new object in one of the lists if values doesn't match比较具有不同对象的两个列表,如果值不匹配,则在其中一个列表中创建新对象
【发布时间】:2019-09-30 15:45:03
【问题描述】:

假设我有两个列表,它们都有对象。 list1 有 5 个对象,list2 有 6 个。我想比较它们并在 list1 中创建新对象,其中包含签入和签出时间,这在 list2 中是额外的。

尝试将它们作为一组进行比较。但没有运气。 谢谢

list1 = [{'checkin': 12/10/2019, 'checkout':13/10/2019},
         {'checkin': 13/10/2019, 'checkout':14/10/2019},
         {'checkin': 14/10/2019, 'checkout':15/10/2019},
         {'checkin': 15/10/2019, 'checkout':16/10/2019},
         {'checkin': 16/10/2019, 'checkout':17/10/2019}]

list2 = [{'checkin': 12/10/2019, 'checkout':13/10/2019},
         {'checkin': 13/10/2019, 'checkout':14/10/2019},
         {'checkin': 14/10/2019, 'checkout':15/10/2019},
         {'checkin': 15/10/2019, 'checkout':16/10/2019},
         {'checkin': 16/10/2019, 'checkout':17/10/2019}
         {'checkin': 20/10/2019, 'checkout':20/10/2019}]

【问题讨论】:

  • 也许显示你到目前为止尝试过的东西......
  • 我不明白你所说的比较是什么意思?您的意思是检查 list1 的项目是否已经在 list2 中以避免新列表中的重复项目?

标签: python django list comparison


【解决方案1】:

如果我正确理解您的问题,您想创建list_1 中的所有项目以及list_2 中但不在list_1 中的项目的列表?

可能是这样的(为简单起见,列表较短):

list_1 = [{'checkin': 12/10/2019, 'checkout':13/10/2019}]
list_2 = [{'checkin': 12/10/2019, 'checkout':13/10/2019}, {'checkin': 19/10/2019, 'checkout':20/10/2019}]


combined_list = list_1 + [x for x in list_2 if x not in list_1]

不要因为dicts而认为我们可以在这里使用set()

【讨论】:

    猜你喜欢
    • 2021-12-03
    • 1970-01-01
    • 2022-11-17
    • 2022-12-31
    • 2018-05-18
    • 2023-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多