python内置迭代对象:
字符串,列表,元组,文件,字典
# 字符串迭代
str = "conding make me happy"
for c in str:
print(c,end = " ")
#列表迭代
lst = ["one","two","three","four","five"]
for l in lst:
print(l,end = " ")
#元组迭代
tpl=("one","two","three","four","five")
for t in tpl:
print(t,end = " ")
#字典迭代
dit={"ua":"coding","age":5}
for key in dit.keys():
print(key,":",dit[key],end=" ")
#文件迭代
fil = open("coding.txt")
for r in fil:
print(r.strip())
上述可迭代对象之所以可以被for循环,因为可迭代对象背后是有迭代器的,但是对我们是不可见的
下面以字符串为例子 使用while进行循环:
str = "conding make me happy"
it = iter(str) # 转换成迭代器
while True:
try:
print(next(it),end=" ")
except StopIteration:
pass
总结:
1. 可迭代对象有一个方法: __iter__,目的是生成迭代器
2. 迭代器有两个方法: __iter__和__next__,__iter__返回迭代器本身, __next__返回单个元素
扩展: 哨符
from random import randint
# 哨符: 可迭代对象边界或者终止值
def sf():
return randint(1,6)
# iter两个参数用法,sf必须是callable
sf_iter = iter(sf,2)
for roll in sf_iter:
print(roll,end = " ")