考虑这个例子?
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
答案 0 :(得分:11)
您可以尝试使用Iterable
模块中的collections
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
答案 1 :(得分: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
注意:尽管Strings是可迭代的,但在python 2中它们没有__iter__
,但在python 3中它们拥有它。因此,在python 2中,您可能也想要or isinstance(f, str)