如何查看特定类型的对象是否在Python列表中?

时间:2014-03-24 19:44:27

标签: python list object

如何检查Python列表中的特定对象类型?例如,我想在列表l中检查ast模块对象下标或_ast.Subscript:

if Subscript in l:
    return True

但这没有奏效。任何有关此问题的帮助将不胜感激。

此外,对象打印为< _ast.Subscript对象,位于0x7ff7f7f7f7ff>

2 个答案:

答案 0 :(得分:5)

使用any

any(isinstance(x, ast.Subscript) for x in lst)

时间比较:

In [20]: from itertools import imap

In [21]: lis = range(10**5) + ['a']

In [22]: %timeit any(isinstance(x, str) for x in lis)
100 loops, best of 3: 18.7 ms per loop

In [23]: %timeit str in map(type, lis)
100 loops, best of 3: 4.28 ms per loop

In [24]: %timeit str in imap(type, lis)                 #winner
100 loops, best of 3: 3.8 ms per loop


In [25]: lis = ['b'] + range(10**5) + ['a']

In [26]: %timeit any(isinstance(x, str) for x in lis)
1000000 loops, best of 3: 533 ns per loop

In [27]: %timeit str in map(type, lis)
100 loops, best of 3: 3.34 ms per loop

In [28]: %timeit str in imap(type, lis)                  #winner
1000000 loops, best of 3: 227 ns per loop


In [29]: lis = range(10**3) + ['a'] + range(10**4)

In [30]: %timeit any(isinstance(x, str) for x in lis)
10000 loops, best of 3: 187 µs per loop

In [31]: %timeit str in map(type, lis)
1000 loops, best of 3: 372 µs per loop

In [32]: %timeit str in imap(type, lis)                  #winner
10000 loops, best of 3: 38.3 µs per loop

imapmap版本之间的差异是imap返回迭代器,因此in上的any调用将与map类似的短路并且它会比mapexcept for tiny-mid sized lists)快,因为any首先在内存中创建一个列表,然后我们检查该项目。 in很慢,因为Python for循环比以{C}速度运行的{{1}}运算符慢。

答案 1 :(得分:3)

见下文:

#if Subscript is an instance of a type
if type(Subscript) in map(type,l):
    return True

# or if Subscript is a type such as a class
if Subscript in map(type,l):
    return True