【问题标题】:How to search for items in a list in python如何在python中搜索列表中的项目
【发布时间】:2016-05-28 05:06:22
【问题描述】:

基本上我有两个项目列表,我想检查第二个列表中的项目是否在第一个列表中。然后,如果该项目在第一个列表中,我想为一个变量分配一个值,如果它不在该列表中,我想为同一个变量分配一个不同的值。 (如下) 这个可以吗?

list1 = ['dog','cat','mouse']

list2 = ['dog','tutle','bird']

if list2 in list1:
    square = 77
else:
    square = 55

print(square)

【问题讨论】:

    标签: python list python-3.x variables if-statement


    【解决方案1】:

    使用set operations:

    if not set(list1).isdisjoint(list2):
    

    如果两个集合没有共同的元素,则它们是不相交的。

    或者使用any() functiongenerator expression 依次测试来自list2 的每个值:

    if any(value in list1 for value in list2):
        square = 77
    else:
        square = 55
    

    甚至:

    square = 77 if any(value in list1 for value in list2) else 55
    

    如果 list1 是一个集合,value in list1 测试会更有效。

    【讨论】:

      【解决方案2】:

      回答你提出的问题:

      list1 = ['dog','cat','mouse']
      list2 = ['dog','tutle','bird']
      for elem in list2:
          if elem in list1:
              square = 77
          else:
              square = 55
          print(elem, "square=", square)
      

      但是搜索列表需要很多时间。您可以通过一组获得一些加速:

      set1 = set(list1)
      for elem in list2:
          if elem in set1:
              square = 77
          else:
              square = 55
          print(elem, "square=", square)
      

      请注意,上面的代码会在 list1 中搜索 list2 中的每个值。如果您想查看 list1 中是否存在 list2 中的任何值,那么应该这样做:

      set1 = set(list1)
      set2 = set(list2)
      if set1.intersection(set2):
          square = 77
      else:
          square = 55
      

      【讨论】:

      • 您正在为list2 中不在list1 中的每个元素设置square = 55square 的值由list2 中的最后一个值决定,这样,其他元素无关紧要。
      • 另外,不要构建然后再次丢弃的集合。你建造了 3 个这样的集合; set2 和交集结果都是完全多余的。 set(list1).isdisjoint(list2) 给你相反的; True 如果没有交集,并且没有构建新集合
      猜你喜欢
      • 2011-10-16
      • 2020-03-13
      • 2010-10-14
      • 2011-09-30
      • 2011-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多