使用生成器和迭代器时,Python多循环失败 [英] Python multi-loop failed when with generator and iterator

查看:149
本文介绍了使用生成器和迭代器时,Python多循环失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个2D循环,其中第一个循环使用迭代器,第二个循环使用生成器,但是这个简单的函数无法工作,任何人都可以帮忙检查吗?

I need a 2D loop of which the first loop uses an iterator and the second uses a generator, but this simple function failed to work, can anyone help to check?

def alphabet(begin, end):
    for number in xrange(ord(begin), ord(end)+1):
        yield chr(number)

def test(a, b):
    for i in a:
        for j in b:
            print i, j

test(xrange(8, 10), alphabet('A', 'C'))

The result shows:
>>> 8 A
>>> 8 B
>>> 8 c

不知道为什么?如果有人可以提供帮助,请提前感谢。

don't know why? thanks in advance if any one can help.

推荐答案

既然你要求澄清,我会说更多一点;但真的 Ignacio 的答案总结得很好:你只能迭代一次发电机。示例中的代码尝试迭代三次,对于 a 中的每个值一次。

Since you've asked for clarification, I'll say a bit more; but really Ignacio's answer sums it up pretty well: you can only iterate over a generator once. The code in your example tries to iterate over it three times, once for each value in a.

要查看我的意思是,考虑这个简单的例子:

To see what I mean, consider this simplistic example:

>>> def mygen(x):
...     i = 0
...     while i < x:
...         yield i
...         i += 1
... 
>>> mg = mygen(4)
>>> list(mg)
[0, 1, 2, 3]
>>> list(mg)
[]

mygen ,它创建一个可以迭代一次的对象。当您尝试再次迭代它时,您将得到一个空的可迭代。

When mygen is called, it creates an object which can be iterated over exactly once. When you try to iterate over it again, you get an empty iterable.

这意味着你必须重新调用 mygen 你想要迭代的每个时间在它上面。所以换句话说(使用相当冗长的风格)......

This means you have to call mygen anew, every time you want to iterate over it`. So in other words (using a rather verbose style)...

>>> def make_n_lists(gen, gen_args, n):
...     list_of_lists = []
...     for _ in range(n):
...         list_of_lists.append(list(gen(*gen_args)))
...     return list_of_lists
... 
>>> make_n_lists(mygen, (3,), 3)
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]

如果你想将你的参数绑定到你的生成器并将其作为无参数函数传递,你可以这样做(使用更简洁的风格):

If you wanted to bind your arguments to your generator and pass that as an argumentless function, you could do this (using a more terse style):

>>> def make_n_lists(gen_func, n):
...     return [list(gen_func()) for _ in range(n)]
... 
>>> make_n_lists(lambda: mygen(3), 3)
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]

lambda 只定义一个匿名函数;以上内容与此相同:

The lambda just defines an anonymous function; the above is identical to this:

>>> def call_mygen_with_3():
...     return mygen(3)
... 
>>> make_n_lists(call_mygen_with_3, 3)
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]

这篇关于使用生成器和迭代器时,Python多循环失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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