检查对象是否是python中的列表列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16367848/
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
Check if object is list of list in python?
提问by Nilesh Agrawal
Is there any ways we can detect if an object is list in python using type(obj)--> list.
有什么方法可以使用type(obj)-->检测对象是否在python中列出list。
But how can we detect if the object is list of list of the form as:
但是我们如何检测对象是否是表单列表的列表:
[['a','b']['a','b'][][]]
回答by Blender
If you want to make sure that everyitem in your list is a list, you could do something like this:
如果您想确保列表中的每个项目都是一个列表,您可以执行以下操作:
if all(isinstance(i, list) for i in lst):
# All of the items are lists
isinstance(i, list)is the better way of writingtype(i) == type(list)ortype(i) == list).all()returnsTrueif all of the items in the sequence areTrue. It'll returnFalseif any aren'tTrue.
isinstance(i, list)是更好的写作方式type(i) == type(list)还是type(i) == list).all()True如果序列中的所有项目都是 ,则返回True。False如果没有,它会返回True。
回答by Martijn Pieters
Use isinstance()to check for a specific type:
使用isinstance()检查特定类型:
>>> isinstance([], list)
True
Use all()to test if allelements are of a certain type:
使用all()如果测试所有的元素是某种类型的:
all(isinstance(elem, list) for elem in list_of_lists)
all()short-circuits; if any of the tests returns False, the loop is terminated and Falseis returned. Only if all but one element returns Truedoes all()need to examine every element of the iterable.
all()短路;如果任何测试返回False,则循环终止并False返回。只有当除一个元素之外的所有元素都返回时True,才all()需要检查可迭代对象的每个元素。

