我似乎在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))


当基础迭代器冗长,无限或计算成本很高时,该方法特别有效。

10-07 17:50