如何检查python中的iterable实例?

bra*_*orm 2 python iterable isinstance

考虑这个例子?

p = [1,2,3,4], (1,2,3), set([1,2,3])]
Run Code Online (Sandbox Code Playgroud)

而不是检查每种类型

for x in p:
   if isinstance(x, list):
      xxxxx
   elif isinstance(x, tuple):
      xxxxxx
   elif isinstance(x, set):
      xxxxxxx
Run Code Online (Sandbox Code Playgroud)

以下是否有一些等价物:

for element in something:
  if isinstance(x, iterable):
      do something
Run Code Online (Sandbox Code Playgroud)

Roc*_*key 12

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

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
Run Code Online (Sandbox Code Playgroud)

  • @cz 这些天Python变化太快了......看看[Pep 585](https://www.python.org/dev/peps/pep-0585/),它说导入`集合中存在的类型`typing` 中的 .abc` 已弃用;在 Python 3.9+ 中从 `collections.abc` 导入它们是正确的方法,在 Python 3.7+ 中使用 `from __future__ import 注解` 是正确的方法。 (4认同)
  • 不推荐从collections导入Iterable,并且在Python 3.8+中会中断。相反,请从“ collections.abc”中导入,例如,从“ collections.abc”中导入Iterable。 (2认同)

the*_*eye 6

您可以检查对象是否具有__iter__属性,以确保它是否可迭代.

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__"))
Run Code Online (Sandbox Code Playgroud)

产量

True
True
True
True
True
False
Run Code Online (Sandbox Code Playgroud)

注意:尽管Strings是可迭代的,但是在python 2中他们没有__iter__,但是在python 3中他们拥有它.所以,在python 2中你可能也想拥有 or isinstance(f, str)

  • 对于可迭代但没有`__iter__`的字符串,这会失败. (3认同)