如何制作这样的可迭代对象? [英] how to make a iterable object like this?

查看:68
本文介绍了如何制作这样的可迭代对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题1

如何制作这样的可迭代对象:

how to make an iterable object like this:

0 1 2 3 4 5 4 3 2 1 0 1 2 3 4 5 4 3 2 1 0 1 2 3 4 5 4 3 2 1 ....

问题2

如果在上面的对象上使用list(obj)会占用机器的内存吗?如何预防呢?

if use list(obj) on the object above would this eat up machine's memory? how to prevent it?

请不要使用python2

Please don't use python2

推荐答案

您可以制作一个可以向上和向下计数的无限生成器:

You can make an infinite generator that counts up and down:

def updown(n):
    while True:
        for i in range(n):
            yield i
        for i in range(n - 2, 0, -1):
            yield i

uptofive = updown(6)
for i in range(20):
    print uptofive.next(),

将输出:

0 1 2 3 4 5 4 3 2 1 0 1 2 3 4 5 4 3 2 1

您不能阻止list(updown(6))尝试消耗所有内存,否.正如医生会说的:那就不要那样做!".

You cannot prevent list(updown(6)) from trying to consume all memory, no. As the doctor would say: "Then don't do that!".

改为使用.next()调用,或将生成器与另一条语句一起使用,该语句限制了对生成器进行迭代的次数. itertools.islice()函数可以做到这一点:

Use .next() calls instead, or use your generator with another statement that limits the number of times you iterate over the generator. The itertools.islice() function would do just that:

import itertools
list(itertools.islice(updown(6), 20))

这篇关于如何制作这样的可迭代对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆