【问题标题】:Python - Check if list of lists of lists contains a specific listPython - 检查列表列表是否包含特定列表
【发布时间】:2014-03-18 15:24:38
【问题描述】:

我有一个列表,其中包含其他列表,其中包含多个图块位置的坐标,我需要检查该列表是否包含另一个坐标列表,如下例所示:

totalList = [ [[0,1], [2,7], [6,3]], [[2,3], [6,1], [4,1]] ]

redList = [ [0,1], [2,7], [6,3] ]

if totalList contains redList:
   #do stuff

你能帮我看看怎么做吗?

【问题讨论】:

    标签: python list


    【解决方案1】:

    只需使用遏制测试:

    if redList in totalList:
    

    这将为您的示例数据返回 True

    >>> totalList = [ [[0,1], [2,7], [6,3]], [[2,3], [6,1], [4,1]] ]
    >>> redList = [ [0,1], [2,7], [6,3] ]
    >>> redList in totalList
    True
    

    【讨论】:

      【解决方案2】:

      使用 in 关键字来确定 list(或任何其他 Python 容器)是否包含元素:

      totalList = [ [[0,1], [2,7], [6,3]], [[2,3], [6,1], [4,1]] ]
      redList = [ [0,1], [2,7], [6,3] ]
      redList in totalList
      

      返回

      True
      

      如果你这样做:

      if redList in totalList:
          #do stuff
      

      然后您的代码将do stuff


      我需要知道 totalList 是否包含与 redList 具有完全相同元素的列表。

      我们看到该列表实现了__contains__

      >>> help(list.__contains__)
      Help on wrapper_descriptor:
      
      __contains__(...)
          x.__contains__(y) <==> y in x
      

      并且来自文档:

      __contains__ Called to implement membership test operators. Should return true if item is in self, false otherwise.

      还有:

      The operators in and not in test for collection membership. x in s 如果 x 是集合 s 的成员,则计算结果为 true,否则为 false。 x not in s 返回 x in s 的否定。集合成员资格测试传统上与序列绑定。如果集合是一个序列并且包含与该对象相等的元素,则该对象是该集合的成员。但是,对于许多其他对象类型来说,支持成员资格测试而不是序列是有意义的。特别是,字典(用于键)和集合支持成员资格测试。

      对于列表和元组类型,x in y 为真当且仅当 存在一个索引 i 使得 x == y[i] 为真。

      所以我们知道其中一个元素必须等于redList的元素。

      【讨论】:

        【解决方案3】:

        只需使用in 运算符:

        >>> totalList = [ [[0,1], [2,7], [6,3]], [[2,3], [6,1], [4,1]] ]
        >>> redList = [ [0,1], [2,7], [6,3] ]
        >>> redList in totalList
        True
        >>> if redList in totalList:
        ...     print('list found')
        ...
        list found
        >>>
        

        来自docs

        运算符innot in 测试成员资格。 x in s 评估为 如果xs 的成员,则为true,否则为false。 x not in s 返回 x in s的否定。

        【讨论】:

          猜你喜欢
          • 2021-10-30
          • 1970-01-01
          • 2019-04-04
          • 1970-01-01
          • 1970-01-01
          • 2019-07-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多