可迭代对象
- 可迭代对象有:集合,列表,字符串,字典,元组
- 不可迭代:整数,浮点数,布尔
迭代器对象
- 调用
obj.__iter__()
方法返回的结果就是一个迭代器对象 - 迭代器对象是内置有
iter
和next
方法的对象,打开的文件本身就是一个迭代器对象- 执行
迭代器对象.iter()
方法得到的仍然是迭代器本身 - 而执行
迭代器对象.next()
方法就会计算出迭代器中的下一个值
- 执行
name = 'heart'
# 获得迭代器的方法一
name_iter = name.__iter__()
# 获得迭代器的方法二
name_iter = iter(name)
# 使用next方法一
print(name_iter.__next__()) # h
print(name_iter.__next__()) # e
print(name_iter.__next__()) # a
# 使用next方法二
print(next(name_iter))
(1)列表
num_list = [1, 2, 3]
num = iter(num_list)
print(next(num)) # 1
print(next(num)) # 2
print(next(num)) # 3
(2)元组
num_list = [1, 2, 3]
num = iter(num_list)
print(next(num)) # 1
print(next(num)) # 2
print(next(num)) # 3
(3)字典
num_list = [1, 2, 3]
num = iter(num_list)
print(next(num)) # 1
print(next(num)) # 2
print(next(num)) # 3
(4)集合
num_list = [1, 2, 3]
num = iter(num_list)
print(next(num)) # 1
print(next(num)) # 2
print(next(num)) # 3
for循环内部原理
num_list = [1, 2, 3, 4, 5, 6]
num_iter = iter(num_list)
while True:
try:
print(num_iter.__next__())
except StopIteration:
break
计时器
import time
start_time = time.time()
print(f'运行时间: {time.time()-start_time}s')
标签:迭代,list,iter,next,num,print
From: https://www.cnblogs.com/ssrheart/p/17897566.html