在python中,测试变量是否包含列表或元组的最佳方法是什么?(即。一组)

isinstance()是否如这里所建议的那样邪恶?http://www.canonical.org/~kragen/isinstance/

更新:我想要区分列表和字符串的最常见原因是,当我有一些无限深嵌套的字符串列表的列表的列表的树/数据结构时,我正在用递归算法探索,我需要知道什么时候我已经碰到了“叶”节点。


当前回答

>>> l = []
>>> l.__class__.__name__ in ('list', 'tuple')
True

其他回答

if type(x) is list:
    print 'a list'
elif type(x) is tuple:
    print 'a tuple'
else:
    print 'neither a tuple or a list'

另一个简单的方法来确定一个变量是列表还是元组,或者检查变量类型:

def islist(obj):
    if ("list" in str(type(obj))):
        return True
    else:
        return False

原则上,我同意上面Ignacio的观点,但是您也可以使用type来检查某个东西是元组还是列表。

>>> a = (1,)
>>> type(a)
(type 'tuple')
>>> a = [1]
>>> type(a)
(type 'list')

你知道的…我这么做可能有点蠢,但我是这么做的

try:
    len(thing)
except:
    # not a list

如果我能知道它的长度,那肯定不止一件事。

编辑:刚刚意识到,如果非列表项是字符串(因为字符串本质上是字符列表),它将不起作用。

我推荐唯一的python方法:

if isinstance(x, (list, tuple))): pass