python 如何在没有循环的情况下检查另一个列表包含的列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2582911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check a list contained by another list without a loop?
提问by Young
As the title mentions,is there any builtins to do this job?I looked for that in dir(list)
but got no usable one.Thanks.
正如标题所提到的,是否有任何内置函数可以完成这项工作?我在里面找过,dir(list)
但没有可用的。谢谢。
回答by nosklo
Depends on what you mean by "contained". Maybe this:
取决于你所说的“包含”是什么意思。也许这个:
if set(a) <= set(b):
print "a is in b"
回答by Etaoin
Assuming that you want to see if all elements of sublist
are also elements of superlist
:
假设您想查看 的所有元素sublist
是否也是 的元素superlist
:
all(x in superlist for x in sublist)
all(x in superlist for x in sublist)
回答by Adrien Plisson
the solution depends on what values you expect from your lists.
解决方案取决于您对列表的期望值。
if there is the possiblity of a repetition of a value, and you need to check that there is enough values in the tested container, then here is a time-inefficient solution:
如果存在重复值的可能性,并且您需要检查测试容器中是否有足够的值,那么这是一个时间效率低的解决方案:
def contained(candidate, container):
temp = container[:]
try:
for v in candidate:
temp.remove(v)
return True
except ValueError:
return False
test this function with:
使用以下命令测试此功能:
>>> a = [1,1,2,3]
>>> b = [1,2,3,4,5]
>>> contained(a,b)
False
>>> a = [1,2,3]
>>> contained(a,b)
True
>>> a = [1,1,2,4,4]
>>> b = [1,1,2,2,2,3,4,4,5]
>>> contained(a,b)
True
of course this solution can be greatly improved: list.remove() is potentially time consuming and can be avoided using clever sorting and indexing. but i don't see how to avoid a loop here...
当然,这个解决方案可以大大改进:list.remove() 可能很耗时,可以使用巧妙的排序和索引来避免。但我不知道如何在这里避免循环......
(anyway, any other solution will be implemented using sets or list-comprehensions, which are using loops internally...)
(无论如何,任何其他解决方案都将使用集合或列表推导来实现,它们在内部使用循环......)