可能会理解迭代器(生成器)与可迭代对象(常用的:字符串、列表、字典...)的性能问题了吧

生成器:我实现了这样一个功能你试试

def count(n):
    while True:
        yield n
        n += 1
        
c = count(0)

列表: 这个简单。


def count(n):
    haha = []
    while True:
        haha.append(n)
        n += 1
    return haha

c = count(0)

都准备好了,点火 开炮

完成后我们来取一下90~100的元素

  • 生成器:ok啦
print(c[90:100])
# 输出
TypeError: 'generator' object is not subscriptable
    
# 正确姿势
import itertools
for i in itertools.islice(c, 90, 100):
    print(i)
    
# 输出
90
91
92
93
94
95
96
97
98
99

  • 列表

蛋定,慢~来
靠,死机了

你可能感兴趣的:(可能会理解迭代器(生成器)与可迭代对象(常用的:字符串、列表、字典...)的性能问题了吧)