3

考虑这个例子?

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
4

2 回答 2

17

您可以尝试使用模块中的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
于 2013-11-12T01:42:09.170 回答
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__"))

输出

True
True
True
True
True
False

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

于 2013-11-12T01:36:59.173 回答