【问题标题】:How to find if a certain element is not present in either of the lists in python [duplicate]如何查找某个元素是否不存在于python中的任何一个列表中[重复]
【发布时间】:2020-06-17 16:57:07
【问题描述】:

我有 2 个列表

lis1=[1,2,3,4,5,6,2,3,1]
lis2=[4,5,8,7,10,6,9,8]

我想编写一个函数,它可以返回存在于lis1lis2 中的元素,输出应该是[1,2,3,7,8,9,10],因为lis2 和7、8、9 中不存在1、2、3, lis1 中没有 10 个

【问题讨论】:

标签: python


【解决方案1】:

如果你不需要排序结果,试试这个:

lis1 = [1, 2, 3, 4, 5, 6, 2, 3, 1]
lis2 = [4, 5, 8, 7, 10, 6, 9, 8]

set1 = set(lis1)
set2 = set(lis2)

print(set1 ^ set2)  # XOR operation for two sets

输出:

{1, 2, 3, 7, 8, 9, 10}

【讨论】:

    【解决方案2】:

    如果你需要得到一个有序的结果:

    lis1=[1,2,3,4,5,6,2,3,1] lis2=[4,5,8,7,10,6,9,8]

    y=11 输入你要检查的最大数量

    for x in range(1, y): if x not in lis1 and x in lis2: print(x) if x not in lis2 and x in lis1: print(x)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-09
      • 2021-09-20
      • 2020-07-07
      • 1970-01-01
      • 2017-04-28
      • 2022-01-06
      • 2013-03-11
      相关资源
      最近更新 更多