【问题标题】:how to check isinstance of iterable in python? [duplicate]如何在python中检查可迭代的isinstance? [复制]
【发布时间】:2013-11-24 00:28:29
【问题描述】:

考虑一下这个例子吗?

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

而不是检查每种类型,例如

for x in p:
   if isinstance(x, list):
      xxxxx
   elif isinstance(x, tuple):
      xxxxxx
   elif isinstance(x, set):
      xxxxxxx

以下是否有等价物:

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

【问题讨论】:

  • 最简单的方法就是尝试迭代它并在它不起作用时捕获异常。

标签: python iterable isinstance


【解决方案1】:

您可以检查对象中是否有__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__"))

输出

True
True
True
True
True
False

注意:尽管字符串是可迭代的,但在 python 2 中它们没有__iter__,但在 python 3 中它们有它。因此,在 python 2 中,您可能还想拥有or isinstance(f, str)

【讨论】:

  • 这对于可迭代但没有__iter__的字符串失败。
  • @Mark 我认为他们有。
  • >>> str.__iter__ <slot wrapper '__iter__' of 'str' objects>
  • @MarkReed 我为字符串部分添加了注释。
  • @aIKid 在 python 3 中,我们有但没有它 python 2
【解决方案2】:

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

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

【讨论】:

  • 从collections 导入Iterable 已被弃用,将在Python 3.8+ 中中断。相反,从collections.abc 导入,例如from collections.abc import Iterable.
  • 如果您希望在 Python 3.8 或更早版本中使用collections.abc.Iterable 作为泛型类型(例如Iterable[int]),您还必须使用from __future__ import annotations
  • @BallpointBen 我认为您将collections.abc.Iterable 与typing.Iterable 混淆了。
  • @cz Python 这些天变化太快了...看看Pep 585,它说从typing 导入存在于collections.abc 中的类型已被弃用;从collections.abc 导入它们是在 Python 3.9+ 和 Python 3.7+ 中使用 from __future__ import annotations 的正确方法。
猜你喜欢
  • 2011-06-07
  • 2016-12-29
  • 2018-08-19
  • 1970-01-01
  • 2021-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-28
相关资源
最近更新 更多