【问题标题】:How to find the value of bool如何找到bool的值
【发布时间】:2022-01-22 15:37:37
【问题描述】:
x =[1,2,3,4,5,6]
y = [1,2,3,4,5]
if x == y:
    print("Numbers found")
else:
    print("Numbers not found")

我想打印列表 y 中不存在的数字。

【问题讨论】:

标签: python list boolean


【解决方案1】:

最快的方法是在集合中转换并打印差异:

>>> print(set(x).difference(set(y)))
{6}

此代码打印存在于x 但不在y 中的数字

【讨论】:

    【解决方案2】:

    你可以这样做:

    x = [1,2,3,4,5,6]
    y = [1,2,3,4,5]
    
    for i in x:
        if i not in y:
            print(i)
    

    【讨论】:

      【解决方案3】:
      x =[1,2,3,4,5,6]
      y = [1,2,3,4,5]
      
      for i in x:
          if i in y:
              print(f"{i} found")
          else:
              print(f"{i} not found")
      

      【讨论】:

        【解决方案4】:

        我认为这是最好的选择。

        x =[1,2,3,4,5,6]
        y = [1,2,3,4,5]
        
        for number in x:
            if number not in y:
                print(f"{number} not found")
        

        【讨论】:

          【解决方案5】:

          获取不匹配:

          def returnNotMatches(a, b):
              return [[x for x in a if x not in b], [x for x in b if x not in a]]
          

          new_list = list(set(list1).difference(list2))
          

          获得交点:

          list1 =[1,2,3,4,5,6]
          list2 = [1,2,3,4,5]
          list1_as_set = set(list1)
          intersection = list1_as_set.intersection(list2)
          

          输出:

          {1, 2, 3, 4, 5}
          

          您也可以将其转移到列表中:

          intersection_as_list = list(intersection)
          

          或:

          new_list = list(set(list1).intersection(list2))
          

          【讨论】:

            猜你喜欢
            • 2013-01-06
            • 1970-01-01
            • 1970-01-01
            • 2013-09-14
            • 2018-06-12
            • 1970-01-01
            • 2019-10-09
            • 2021-09-30
            • 2011-04-04
            相关资源
            最近更新 更多