【问题标题】:Compare between lists with different lengths?比较不同长度的列表?
【发布时间】:2021-03-18 14:58:26
【问题描述】:

我正在比较两个不同的列表。我需要获取每个列表的唯一元素(其他列表中没有的元素)。

每个新列表都包含另一个列表中不存在的内容。

例如:

list1 = ['apple', 'coffee', 'orange', 'sugar']
list2 = ['apple', 'grape', 'orange', 'eggplant', 'pineapple']

预期输出

new_list1 = ['coffee', 'sugar']
new_list2 = ['grape', 'eggplant', 'pineapple']

【问题讨论】:

    标签: python list loops methods


    【解决方案1】:

    如果您只需要每个列表中的唯一元素而不将它们放在单独的列表中,请使用 XOR 运算符而不是差异:

    list1 = ['apple', 'coffee', 'orange', 'sugar']
    list2 = ['apple', 'grape', 'orange', 'eggplant', 'pineapple']
    
    unique = set(list1) ^ set(list2)
    

    【讨论】:

      【解决方案2】:

      您可以像这样优化上述解决方案:

      >>> list(set(list1)-set(list2))
      ['coffee', 'sugar']
      >>> list(set(list2)-set(list1))
      ['eggplant', 'grape', 'pineapple']
      

      【讨论】:

        【解决方案3】:

        简单的循环示例,但不一定是最有效的:

        new_list_1 = [item for item in list1 if item not in list2]
        new_list_2 = [item for item in list2 if item not in list1]
        

        【讨论】:

          【解决方案4】:

          最直接的方法是使用sets

          例子:

          list1 = set(['apple', 'coffee', 'orange', 'sugar'])
          list2 = set(['apple', 'grape', 'orange', 'eggplant', 'pineapple'])
          
          new_list1 = list(list1 - list2)
          new_list2 = list(list2 - list1)
          

          【讨论】:

            猜你喜欢
            • 2021-02-25
            • 2017-12-24
            • 1970-01-01
            • 2023-01-13
            • 1970-01-01
            • 2018-12-07
            • 1970-01-01
            • 1970-01-01
            • 2018-07-03
            相关资源
            最近更新 更多