Python迭代器 —— 实现for循环
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python迭代器 —— 实现for循环相关的知识,希望对你有一定的参考价值。
Python的for循环本质上就是通过不断调用next()函数实现的,例如:
1 #_*_coding:utf-8_*_ 2 #__author__ = "csy" 3 d = ["咖啡浆果风味拿铁","抹茶星冰乐","可可碎片星冰乐","焦糖玛奇朵","经典巧克力","咖啡密斯朵","热牛奶","东方美人","冰摩卡","卡布奇诺","美式咖啡","双果果汁"] 4 a = iter([0,1,2,3,4,5,6,8,9,10,11]) 5 while True: 6 try: 7 x = next(a) 8 print(d[x]) 9 except StopIteration: 10 break
输出:
咖啡浆果风味拿铁
抹茶星冰乐
可可碎片星冰乐
焦糖玛奇朵
经典巧克力
咖啡密斯朵
热牛奶
冰摩卡
卡布奇诺
美式咖啡
双果果汁
相当于:
1 #_*_coding:utf-8_*_ 2 #__author__ = "csy" 3 d = ["咖啡浆果风味拿铁","抹茶星冰乐","可可碎片星冰乐","焦糖玛奇朵","经典巧克力","咖啡密斯朵","热牛奶","东方美人","冰摩卡","卡布奇诺","美式咖啡","双果果汁"] 4 for x in range(0,12): 5 print(d[x])
以上是关于Python迭代器 —— 实现for循环的主要内容,如果未能解决你的问题,请参考以下文章