如何在python中检查iterable的isInstance?

how to check isinstance of iterable in python?

本问题已经有最佳答案,请猛点这里访问。

考虑这个例子?

1
p = [1,2,3,4], (1,2,3), set([1,2,3])]

而不是检查每种类型

1
2
3
4
5
6
7
for x in p:
   if isinstance(x, list):
      xxxxx
   elif isinstance(x, tuple):
      xxxxxx
   elif isinstance(x, set):
      xxxxxxx

是否存在以下方面的等价物:

1
2
3
for element in something:
  if isinstance(x, iterable):
      do something


您可以尝试使用collections模块中的Iterableabc:

1
2
3
4
5
6
7
8
9
10
11
12
In [1]: import collections

In [2]: p = [[1,2,3,4], (1,2,3), set([1,2,3]), 'things', 123]

In [3]: for item in p:
   ...:     print isinstance(item, collections.Iterable)
   ...:    
True
True
True
True
False

您可以检查对象中是否有__iter__属性,以确定它是否可以。

1
2
3
4
5
6
7
8
9
10
11
12
a = [1, 2, 3]
b = {1, 2, 3}
c = (1, 2, 3)
d = {"a": 1}
f ="Welcome"
e = 1
print (hasattr(a,"__iter__"))
print (hasattr(b,"__iter__"))
print (hasattr(c,"__iter__"))
print (hasattr(d,"__iter__"))
print (hasattr(f,"__iter__") or isinstance(f, str))
print (hasattr(e,"__iter__"))

产量

1
2
3
4
5
6
True
True
True
True
True
False

注意:尽管字符串是不可重复的,但在python2中它们没有__iter__,但在python3中它们有。所以,在python2中,您可能也希望使用or isinstance(f, str)