【问题标题】:Check a list of lists for a specific value in Python? [duplicate]检查 Python 中特定值的列表列表? [复制]
【发布时间】:2015-10-28 01:31:09
【问题描述】:

我有

list_of_lists = [ ['a', 'b', 'c'] , ['b','c'] , ['c'] ]

我想确定是否

'd' 

是我的列表的成员。我该如何在 Python 中做到这一点?

【问题讨论】:

  • 'd' in itertools.chain.from_iterable(list_of_lists)
  • 我只会使用 for 循环:any('d' in sub for sub in list_of_lists)
  • 为什么上面的评论框里有answers?当然,将它们放在下面的 answer 框中会更好:-)

标签: python list


【解决方案1】:

您的问题(“d”是否是我的列表中的成员)的准确答案是

'd' in list_of_lists

但我怀疑你的问题措辞不当

如果您的问题是 'd' 是否是 list_of_lists 项目之一的成员,那么答案是

any('d' in lst for lst in list_of_lists)

【讨论】:

    【解决方案2】:

    我们可以定义一个函数,所以它可以处理任意嵌套列表。

    def flatten(container):
        for item in container:
            if isinstance(item, list):
               for inner_item in flatten(item):
                   yield inner_item
            else:
               yield item
    
    >>> 'd' in flatten([['a', 'b', 'c'], ['b','c'], ['c']])
    False
    >>> 'd' in flatten([['a', 'b', 'c'], ['b','c', ['d']], ['c']])
    True
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-27
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      • 2021-10-30
      • 2016-01-31
      • 1970-01-01
      相关资源
      最近更新 更多