Python迭代器

"""
迭代器: 不依赖索引取值的 一种取值方式
  1、可迭代对象: 对象有 __iter__() 就是可迭代对象
  2、可迭代对象.__iter__() 返回一个迭代器对象
  3、迭代器对象.__next__()  迭代取值 直到取干净为止(StopIteration)
"""
# 哪些是可迭代对象?
# str 字符串
'123'.__iter__()
# list 列表
[1,2,3].__iter__()
# tuple 元组
(1,2).__iter__()
# dict 字典
{'a':1, 'b':2}.__iter__()
# set 集合
{1,2,3}.__iter__()
with open('111.txt', 'w', encoding='utf-8') as f:
    f.__iter__()

# 索引取值 与 迭代取值
l = [1, 3, 5]

# 方式一: 索引取值
index = 0
while True:
    try:
        print('索引', l[index])
        index += 1
    except IndexError:
        break

# 方式二: 迭代(非索引)取值
l_iterator = l.__iter__()

while True:
    try:
        print('迭代', l_iterator.__next__())
    except StopIteration:
        break

# 方式二的升级版: for循环
# 1、for循环会帮我们先通过 l.__iter__() 得到一个迭代器对象
for i in l:
    # 2、自动调用 迭代器对象.__next__() 方法 获取返回值 并将返回值 赋值给 i
    print('for循环', i)
    # 3、重复步骤2  
    #    直到迭代器对象.__next__() 取不到值 抛出StopIteration异常 
    #    for循环自动结束循环
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值