如何检查对象是列表还是元组(但不是字符串)? [英] How to check if an object is a list or tuple (but not string)?
问题描述
为了确定输入是 list
/tuple
而不是 str
,我通常会这样做.因为很多时候我偶然发现了一个错误,其中一个函数错误地传递了一个 str
对象,并且目标函数执行 for x in lst
假设 lst
实际上是一个 list
或 tuple
.
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屋!