2013-04-28 148 views
1

我似乎做了很多(不管是不是我应该或许是另一个话题)在我的Python代码:为*铸造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()) 
+7

怎么样'the_list =名单(get_list_generator())'? – 2013-04-28 19:14:33

回答

1

没有将迭代器转换为列表的语法快捷方式。所以只是运行list(it)是惯例。

如果您需要的是只检查的结果,使用取()配方从itertools模块里:

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

这配方效果特别好,当底层迭代器是漫长的,无限的,还是贵计算。

+0

对于我的交互式场景来说,这实际上相当不错,我很少想要将整个迭代转换为列表。经过一些测试后,我发现它非常容忍输入。它会处理列表和迭代器(所以我不必付出太多的关注),并且似乎没有抱怨如果范围是错误的(它只是返回空列表)。因此,为了保持我的交互式历史日志清洁,这个技巧就是了(我会马上把它称为通常避免我原来需要第二次重新分配)。 – user2097818 2013-04-28 20:59:14

1

没有

增强分配只能由结合运营assignement工作。 list(...)功能调用而不是操作员。您可以找到可能的扩充作业清单here

如果您想避免执行两个作业,请立即拨打list

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) 
+0

在交互模式下使用时,这需要更多的深思熟虑,但仍然非常灵活,快速应用,而且绝对是我原先想到的*速记类型。 – user2097818 2013-04-28 21:11:58