[英]How do I search a list that is in a nested list (list of list) without loop in Python?
I am perfectly aware of that.. 我完全清楚这一点......
sample=[[1,[1,0]],[1,1]]
[1,[1,0]] in sample
This will return True. 这将返回True。
But what I want to do here is this. 但我想在这里做的就是这个。
sample=[[1,[1,0]],[1,1]]
[1,0] in sample
I want the return to be True, but this returns False. 我希望返回为True,但返回False。 I can do this:
我可以做这个:
sample=[[1,[1,0]],[1,1]]
for i in range(len(sample)):
[1,0] in sample[i]
But I am wondering if there is any better or efficient way of doing it. 但我想知道是否有更好或更 有效的方法。
you can use chain from itertools to merge the lists and then search in the returned list. 您可以使用来自itertools的链来合并列表,然后在返回的列表中进行搜索。
>>> sample=[[1,[1,0]],[1,1]]
>>> from itertools import chain
>>> print [1,0] in chain(*sample)
True
A recursive solution that would work for arbitrary (max recursion depth aside) deep nesting. 一种递归解决方案,适用于任意(最大递归深度)深度嵌套。 Also works if any elements of the outermost list are not iterables themselves.
如果最外面的列表的任何元素本身不是可迭代的,也可以工作。
from functools import partial
def contains_nested(some_iterable, elmnt):
try:
if elmnt in some_iterable:
return True
except TypeError: # some_iterable is not iterable
return False
else:
return any(map(partial(contains_nested, elmnt=elmnt), some_iterable))
I don't know how to solve this completely without a loop. 我不知道如何在没有循环的情况下彻底解决这个问题。 But in Python you should never write
for i in range(len(sample))
. 但是在Python中,你永远不应该
for i in range(len(sample))
编写for i in range(len(sample))
。
So the answer to your question: Yes there is a better and faster way you could loop your list for i in sample
所以你的问题的答案是:是的,有一种更好,更快的方法可以循环你的
for i in sample
列表
The way Python handles the loops is really fast and works also very well with a lot of entriey (more than 50.000). Python处理循环的方式非常快,并且非常适用于大量的entriey(超过50.000)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.