千里之行,始于足下
print(type(range(10)))
结果:<class 'range'>
了解一下常用的range函数式什么类型的
# 平方表
square_table = []
for i in range(5000):
square_table.append(i * i)
for i in range(5):
print(square_table[i])
结果 :0
1
4
9
16使用for循环添加5000以内的平方数,打印前五个平方数
square_generator = (x * x for x in range(50000))
print(type(square_generator))
for i in range(5):
print(next(square_generator))
结果 :<class 'generator'>
0
1
4
9
16换一种形式实现,使用generator函数实现,每调用一次next()函数产生一个数
ef fib(limit):
n, a, b = 0, 0, 1
while n < limit:
yield b
a, b = b, a + b
n += 1
return 'done'
import traceback
f = fib(5)
print(type(f))
print(next(f))
print(next(f))
print(next(f))
print(next(f))
print(next(f))
try:
print(next(f))
except StopIteration:
traceback.print_exc()
for i in fib(5):
print(i)
结果 :<class 'generator'>
1
1
2
3
5
1
1
2
3
5
Traceback (most recent call last):
File "C:/Users/liuyue/PycharmProjects/test/generator.py", line 32, in <module>
print(next(f))
StopIteration: done打印一下斐波那契数列,可以不断调用next()函数产生数字,f包含5个数,如果调用第六次的时候会抛出StopIteration
也可直接循环打印,不调用next(),每次被调用后数字都会自动增加