如何在Python中没有循环的情况下搜索嵌套列表(列表列表)中的列表?

Kiw*_*Lee 13 python list

我完全清楚这一点......

sample=[[1,[1,0]],[1,1]]
[1,[1,0]] in sample
Run Code Online (Sandbox Code Playgroud)

这将返回True.

但我想在这里做的就是这个.

sample=[[1,[1,0]],[1,1]]
[1,0] in sample
Run Code Online (Sandbox Code Playgroud)

我希望返回为True,但返回False.我可以做这个:

sample=[[1,[1,0]],[1,1]]
for i in range(len(sample)):
    [1,0] in sample[i]
Run Code Online (Sandbox Code Playgroud)

但我想知道是否有更好有效的方法.

Ale*_*lex 6

您可以使用来自itertools的链来合并列表,然后在返回的列表中进行搜索.

>>> sample=[[1,[1,0]],[1,1]]
>>> from itertools import chain
>>> print [1,0]  in chain(*sample)
True
Run Code Online (Sandbox Code Playgroud)

  • 问题是列表清单.如果你想在任意结构中找到列表,这将进入解析区域.模式匹配或访客可能适用的地方.(请注意,两者都需要遍历一组已知结构). (2认同)