1

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

3 回答 3

1

增强赋值只能通过将运算符与赋值相结合来工作。list(...)函数调用而不是运算符。您可以在此处找到可能的扩充作业列表

如果你想避免做两个任务,只需list立即调用。

于 2013-04-28T19:17:59.833 回答
1

没有将迭代器转换为列表的语法快捷方式。所以只是跑步list(it)是通常的做法。

如果您只需要检查结果,请使用 itertools 模块中的take()配方:

def take(n, iterable):
    "Return first n items of the iterable as a list"
     return list(islice(iterable, n))

当底层迭代器冗长、无限或计算成本高昂时,该方法特别有效。

于 2013-04-28T20:25:41.447 回答
1

也许你可以采取不同的方式:

如果你有一个想要返回 a 的生成器函数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)
于 2013-04-28T20:50:29.187 回答