这个生成器函数如何变成生成器表达式呢?
How can this generator function be turned into a generator expression?
我编写了一个生成器函数,它以与 Excel 等电子表格应用程序中的列命名方案相同的方式生成无限的字符串序列,例如:
'', 'A', 'B', ... 'Z', 'AA', 'AB', ... 'AZ', 'BA', ... 'ZZ', 'AAA', ...
我的函数运行没有任何问题:
def __suffix_generator():
len, gen = (0, iter(['']))
while True:
try:
suffix = next(gen)
except StopIteration:
len += 1
gen = itertools.product(string.ascii_uppercase, repeat=len)
suffix = next(gen)
yield ''.join(suffix)
但是,我想把它变成一个更惯用的版本,它只使用生成器表达式,到目前为止我最好的镜头是这样的:
def __suffix_generator_gexp():
from itertools import product, count
from string import ascii_uppercase
return (''.join(suffix) for suffix in
(product(ascii_uppercase, repeat=len) for len in count()))
使用该生成器时,我收到运行时类型错误,它告诉我 suffix
变量的类型未被接受:
TypeError: sequence item 0: expected string, tuple found
我的假设是 suffix
应该是一个包含特定组合字母的元组,并且 join
会将其转换为字符串。我怎样才能让它像第一个功能一样正常工作?
也许这就是您要找的:
map(''.join, chain.from_iterable(product(ascii_uppercase, repeat=l) for l in count(1)))
count(n)
使用 step = 1
生成以 n
开头的数字序列,因此每个数字 N_{t+1} = N_t + step
和 N_1 = n
.
如果您正在使用 Python 2.x,map
将尝试构建一个列表但会失败,因此您可以这样做:
(''.join(perm) for perm in (...))
其中 ...
是第一个代码段中 map
的第二个参数。
我编写了一个生成器函数,它以与 Excel 等电子表格应用程序中的列命名方案相同的方式生成无限的字符串序列,例如:
'', 'A', 'B', ... 'Z', 'AA', 'AB', ... 'AZ', 'BA', ... 'ZZ', 'AAA', ...
我的函数运行没有任何问题:
def __suffix_generator():
len, gen = (0, iter(['']))
while True:
try:
suffix = next(gen)
except StopIteration:
len += 1
gen = itertools.product(string.ascii_uppercase, repeat=len)
suffix = next(gen)
yield ''.join(suffix)
但是,我想把它变成一个更惯用的版本,它只使用生成器表达式,到目前为止我最好的镜头是这样的:
def __suffix_generator_gexp():
from itertools import product, count
from string import ascii_uppercase
return (''.join(suffix) for suffix in
(product(ascii_uppercase, repeat=len) for len in count()))
使用该生成器时,我收到运行时类型错误,它告诉我 suffix
变量的类型未被接受:
TypeError: sequence item 0: expected string, tuple found
我的假设是 suffix
应该是一个包含特定组合字母的元组,并且 join
会将其转换为字符串。我怎样才能让它像第一个功能一样正常工作?
也许这就是您要找的:
map(''.join, chain.from_iterable(product(ascii_uppercase, repeat=l) for l in count(1)))
count(n)
使用 step = 1
生成以 n
开头的数字序列,因此每个数字 N_{t+1} = N_t + step
和 N_1 = n
.
如果您正在使用 Python 2.x,map
将尝试构建一个列表但会失败,因此您可以这样做:
(''.join(perm) for perm in (...))
其中 ...
是第一个代码段中 map
的第二个参数。