我似乎在我的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())
最佳答案
没有将迭代器转换为列表的语法快捷方式。因此,通常的做法是运行 list(it)
。
如果您只需要检查结果,请使用 itertools 模块中的 take() 配方:
def take(n, iterable):
"Return first n items of the iterable as a list"
return list(islice(iterable, n))
当底层迭代器很长、无限或计算成本很高时,该方法尤其有效。
关于*casting* 的 Python 赋值简写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16266690/