name 'iterable' is not defined 在python中判断一个对象是否可迭代

465 阅读2分钟

如果一个对象可迭代意味着可以通过for循环去操作处理它,那么在python中怎样判断一个对象是否可直接迭代?如何生成或将一个对象转化为可迭代的对象呢?

1. 判断对象是否是迭代器(iterator)

# 列表list对象
In [9]: isinstance([1,2,3],Iterable)                                            
Out[9]: True

# 集合set对象
In [12]: isinstance((1,2,3),Iterable)                                           
Out[12]: True

# 字符串string对象
In [13]: isinstance('hello word!',Iterable)                                     
Out[13]: True

# 字典dict对象
In [15]: isinstance({'city_no':10001,'city_name':'上海市'},Iterable)            
Out[15]: True

# 元组tuple对象
In [16]: isinstance(((1001,'上海市'),(1003,'深圳市')),Iterable)                 
Out[16]: True

# pandas.core.series.Series对象
In [17]: lost_custs = pd.read_excel('./data_20200510.xlsx')
isinstance(lost_custs['vin'],Iterable)
In [18]: True

如果报错,需要先从collections包中引入Iterable

In [3]: from collections import Iterable                                        
<ipython-input-3-c0513a1e6784>:1: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.9 it will stop working
  from collections import Iterable

2.将一个对象转化为可迭代(iterable)

  • 如果一个对象已经是一个可迭代的对象,可以直接在for循环中操作它的每一个元素;
  • 相反,如果一个对象是不可迭代的,直接使用for循环去操作它,就会收到一个报错,提示这个对象是不可迭代的。
In [20]: for t in ((1001,'上海市'),(1003,'深圳市')): 
    ...:     print(t) 
    ...:                                                                        
(1001, '上海市')
(1003, '深圳市')

这个元组对象本身就是可迭代的,所以可以直接用for循环操作处理它的每一个组成元素。

如果一个对象不可直接迭代,又需要在for循环中操作它,那么尝试先将其转化为可迭代的对象。比如:

v_list = list(lost_custs['vin'])

欢迎👏👏👏
关注微信公众号:数据分析师之家

在这里插入图片描述