問題描述
我需要一個 2D 循環(huán),其中第一個循環(huán)使用迭代器,第二個循環(huán)使用生成器,但是這個簡單的函數(shù)無法工作,誰能幫忙檢查一下?
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
不知道為什么?如果有人可以提供幫助,請?zhí)崆爸轮x.
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
被調用時,它會創(chuàng)建一個可以只迭代一次的對象.當您嘗試再次對其進行迭代時,您會得到一個空的可迭代對象.
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]]
如果您想將參數(shù)綁定到生成器并將其作為無參數(shù)函數(shù)傳遞,您可以這樣做(使用更簡潔的樣式):
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
只是定義了一個匿名函數(shù);以上與此相同:
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 多循環(huán)失敗的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!