测试变量是列表还是元组 [英] Test if a variable is a list or tuple
问题描述
在python中,测试变量是否包含列表或元组的最佳方法是什么? (即集合)
In python, what's the best way to test if a variable contains a list or a tuple? (ie. a collection)
isinstance()
是否像这里建议的那样邪恶? http://www.canonical.org/~kragen/isinstance/
Is isinstance()
as evil as suggested here? http://www.canonical.org/~kragen/isinstance/
更新:我要从字符串中区分列表的最常见原因是当我有一些无限深的嵌套树/字符串列表等列表的数据结构时,我正在使用递归算法进行探索.而且我需要知道何时击中叶子"节点.
Update: the most common reason I want to distinguish a list from a string is when I have some indefinitely deep nested tree / data-structure of lists of lists of lists of strings etc. which I'm exploring with a recursive algorithm and I need to know when I've hit the "leaf" nodes.
推荐答案
如果需要,请继续使用isinstance
.这有点邪恶,因为它不包括自定义序列,迭代器和您可能实际需要的其他东西.但是,有时,例如,有人传递字符串时,您需要采取不同的行为方式.我的喜好是像这样显式检查str
或unicode
:
Go ahead and use isinstance
if you need it. It is somewhat evil, as it excludes custom sequences, iterators, and other things that you might actually need. However, sometimes you need to behave differently if someone, for instance, passes a string. My preference there would be to explicitly check for str
or unicode
like so:
import types
isinstance(var, types.StringTypes)
不要将types.StringType
误认为types.StringTypes
.后者包含str
和unicode
对象.
N.B. Don't mistake types.StringType
for types.StringTypes
. The latter incorporates str
and unicode
objects.
许多人认为types
模块已过时,只支持直接检查对象的类型,因此,如果您不想使用以上内容,则可以选择明确地检查str
和unicode
,就像这样:
The types
module is considered by many to be obsolete in favor of just checking directly against the object's type, so if you'd rather not use the above, you can alternatively check explicitly against str
and unicode
, like this:
isinstance(var, (str, unicode)):
更好的是:
isinstance(var, basestring)
结束编辑
在上述任何一种情况下,您都可以回到正常的序列状态,让非序列引发适当的异常.
After either of these, you can fall back to behaving as if you're getting a normal sequence, letting non-sequences raise appropriate exceptions.
看到类型检查的邪恶"之处不是您可能不想对某种特定类型的对象表现出不同的行为,而是您人为地限制了函数对意外对象类型进行正确操作的方式,否则将无法执行正确的事.如果您有未经过类型检查的最终后备,则可以删除此限制.应该注意的是,过多的类型检查是一种代码异味,表明您可能想要进行一些重构,但这并不一定意味着您应该避免从getgo中进行此操作.
See the thing that's "evil" about type checking is not that you might want to behave differently for a certain type of object, it's that you artificially restrict your function from doing the right thing with unexpected object types that would otherwise do the right thing. If you have a final fallback that is not type-checked, you remove this restriction. It should be noted that too much type checking is a code smell that indicates that you might want to do some refactoring, but that doesn't necessarily mean you should avoid it from the getgo.
这篇关于测试变量是列表还是元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!