[英]How can I see if a list contains another list in Python?
How would I check to see if a list contains other lists? 我如何检查列表是否包含其他列表? I need it so that
我需要它
[['cow'], 12, 3, [[4]]]
would output True
, while something like 将输出
True
,而类似的东西
['cow', 12, 3, 4]
would output False
. 会输出
False
。
If you also want to find subclasses of lists then you should use isinstance
: 如果您还想查找列表的子类,那么您应该使用
isinstance
:
def any_list_in(obj):
return any(isinstance(item, list) for item in obj)
any
stops as soon as the condition is True
so this only needs to check only as many items as necessary. 条件为
True
any
停止,因此只需要检查所需的项目数。
>>> any_list_in([['cow'], 12, 3, [[4]]])
True
>>> any_list_in(['cow', 12, 3, 4])
False
The isinstance(item, list) for item in obj
is a generator expression that works similar to a for
-loop or a list-comprehension. isinstance(item, list) for item in obj
的isinstance(item, list) for item in obj
是一个生成器表达式 ,其工作方式类似于for
-loop或list-comprehension。 It could also be written as (longer and slightly slower but maybe that's better to comprehend): 它也可以写成(更长和稍慢但可能更好理解):
def any_list_in(obj):
for item in obj:
if isinstance(item, list):
return True
return False
Here's a neat solution using a list comprehension. 这是一个使用列表理解的简洁解决方案。
Given obj = [['cow'], 12, 3, [[4]]]
, we'll first use a list comprehension to get a list of types in obj
: 给定
obj = [['cow'], 12, 3, [[4]]]
,我们将首先使用列表推导来获取obj
中的类型列表:
>>> [type(x) for x in obj]
[<type 'list'>, <type 'int'>, <type 'int'>, <type 'list'>]
Now, we simply check if list
is in the list of types we created. 现在,我们只需检查
list
是否在我们创建的类型列表中。 Let's revisit our list comprehension and turn it into a boolean expression: 让我们重新审视列表理解并将其转换为布尔表达式:
>>> list in [type(x) for x in obj]
There, that's nice and short. 那里,这很好,很短。 So does it work?
它有用吗?
>>> obj = [['cow'], 12, 3, [[4]]]
>>> list in [type(x) for x in obj]
True
>>> obj = ['cow', 12, 3, 4]
>>> list in [type(x) for x in obj]
False
You can use this method if your list does not contain some string with '[' int it . 如果列表中没有包含'['int'的字符串,则可以使用此方法。
def check(a):
a=str(a)
if a.count('[')==1: # or a.count(']')==1;
return False
return True
In python 2.7 we have a module for this work:( I don't know about any such module in python 3.x ) 在python 2.7中我们有一个模块用于这项工作:(我不知道python 3.x中的任何这样的模块)
from compiler.ast import flatten
def check(a):
if flatten(a)==a:
return False
return True
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.