判断是否为可迭代对象

有的时候,难免会忘记哪种数据类型为可迭代对象,怎么办呢?简单:我们仅需要导入一个模块,判断一下即可:

 

from collections.abc import Iterable
res = map(lambda x:x**2,[1,5,7,4,8])

print(isinstance(res,Iterable)) #True代表可迭代

建议写from collections.abc import Iterable因为:from collections import Iterable在python 3.8及更高级版本停止使用,会报出一个这样的警告。

 

DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working from collections import Iterable

 

posted @ 2019-04-14 16:04  上古战神  阅读(500)  评论(0编辑  收藏  举报