我似乎在我的python代码中做了很多事情(无论我是否应该是另一个话题):
the_list = get_list_generator()
#So `the_list` is a generator object right now
#Iterate the generator pulling the list into memory
the_list = list(the_list)
在进行算术作业时,我们有像这样的短序......
the_number += 1
那么,在使用函数进行赋值时,是否有某种方法可以实现相同的速记。我不知道是否有内置功能可以执行此操作,或者我是否需要定义自定义运算符(我从未这样做过),或者其他一些最终导致清洁代码的方法 (我保证我只会将它用于通用类型转换)。
#Maybe using a custom operator ?
the_list @= list()
#Same as above, `the_list` was a generator, but is a list after this line
修改::
我最初没有提到:这种情况最常发生在交互模式中(因此我希望减少所需的打字)。我将尝试索引迭代器gen_obj[3]
,得到一个错误,然后必须强制转换它。
正如所建议的那样,这可能是最好的,但最终还不是我想要的。
the_list = list(get_list_generator())
答案 0 :(得分:1)
答案 1 :(得分:1)
没有将迭代器转换为列表的语法快捷方式。因此,只需运行list(it)
即可。
如果您只需要检查结果,请使用itertools模块中的 take()配方:
def take(n, iterable):
"Return first n items of the iterable as a list"
return list(islice(iterable, n))
当底层迭代器计算冗长,无限或昂贵时,该配方工作得特别好。
答案 2 :(得分:1)
也许你可以采用不同的方式:
如果你有一个你希望返回list
的生成器函数,你可以装饰它。
def apply(after):
import functools
"Apply a function to the result of a function call."
def decorator(func):
@wraps(func)
def wrapper(*a, **k):
return after(func(*a, **k))
return wrapper
return decorator
拥有此功能后,您可以这样使用它:
@apply(list)
def get_list_generator(n):
yield n
l = get_list_generator(12)