如何检查对象是列表还是元组(而不是字符串)? [英] How to check if an object is a list or tuple (but not string)?
问题描述
这是我通常要执行的操作,以确定输入是list
/tuple
-而不是str
.因为很多时候我偶然发现了一个错误,即一个函数错误地传递了一个str
对象,而目标函数却假定lst
实际上是一个list
或tuple
来执行for x in lst
.
This is what I normally do in order to ascertain that the input is a list
/tuple
- but not a str
. Because many times I stumbled upon bugs where a function passes a str
object by mistake, and the target function does for x in lst
assuming that lst
is actually a list
or tuple
.
assert isinstance(lst, (list, tuple))
我的问题是:有没有更好的方法来实现这一目标?
My question is: is there a better way of achieving this?
推荐答案
仅在python 2中(不是python 3):
In python 2 only (not python 3):
assert not isinstance(lst, basestring)
实际上就是您想要的,否则您会错过很多像列表一样的东西,但它们不是list
或tuple
的子类.
Is actually what you want, otherwise you'll miss out on a lot of things which act like lists, but aren't subclasses of list
or tuple
.
这篇关于如何检查对象是列表还是元组(而不是字符串)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!