迭代器python的优势_迭代器是否在Python中节省内存?

I don't quite understand how iterators have memory in Python.

>>> l1 = [1, 2, 3, 4, 5, 6]

>>> l2 = [2, 3, 4, 5, 6, 7]

>>> iz = izip(l1, l2)

We still require O(min(l1, l2)) memory as we need to load the lists l1 and l2 in memory.

I thought one of the main uses of iterators was to save memory - yet it does not seem to be useful here.

Similarly, the code below is unclear to me:

>>> l1 = ( n for n in [1, 2, 3, 4, 5, 6] )

>>> l2 = ( n for n in [2, 3, 4, 5, 6, 7] )

>>> iz = izip(l1, l2)

We need to load the lists before converting them into generators, right? This means we'll waste memory. So - what is the point of generators here as well.

This is the only case that makes sense to me:

def build_l1():

for n in xrange(1, 6):

yield n

def build_l2:

for n in xrange(2, 7):

yield n

l1 = build_l1()

l2 = build_l2()

iz = izip(l1, l2)

None of the arrays is being loaded into memory. Hence we're in O(1) memory.

How does the memory usage of the iterator functions in Python work? The first two cases seem to use O(min(l1, l2)) memory. I thought the main point of iterators was to save memory, which makes the first two cases seem useless.

解决方案

Your examples are too simplistic. Consider this:

nums = [1, 2, 3, 4, 5, 6]

nums_it = (n for n in nums)

nums_it is a generator that returns all items unmodified from nums. Clearly you do not have any advantage. But consider this:

squares_it = (n ** 2 for n in nums)

and compare it with:

squares_lst = [n ** 2 for n in nums]

With squares_it, we are generating the squares of nums on the fly only when requested. With squares_lst, we are generating all of them at once and storing them in a new list.

So, when you do:

for n in squares_it:

print(n)

it's like if you were doing:

for n in nums:

print(n ** 2)

But when you do:

for n in squares_lst:

print(n)

it's like if you were doing:

squares_lst = []

for n in nums:

squares_lst.append(n ** 2)

for n in squares_lst:

print(n)

If you don't need (or don't have) the list nums, then you can save even more space by using:

squares_it = (n ** 2 for n in xrange(1, 7))

Generators and iterators also provide another significant advantage (which may actually be a disadvantage, depending on the situation): they are evaluated lazily.

Also, generators and iterators may yield an infinite number of elements. An example is itertools.count() that yields 0, 1, 2, 3, ... without never ending.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值