简体   繁体   English

迭代解包在第一次迭代后导致空对象

[英]iterable unpacking results in empty object after first iteration

Using the * iterable unpacking operator features I would like to maintain the content of a variable so that I can use the variable at multiple places in my code. 使用* iterable解包操作符功能我想保留变量的内容,以便我可以在我的代码中的多个位置使用该变量。 Here is a little example expressing what I would like: 这是一个表达我想要的例子:

>>> a = 1
>>> b = None
>>> c = None
>>> args = (x for x in (a, b, c) if x is not None)
>>> print(*args)
>>> 1
>>> print(*args)
>>> 

The second print returns nothing because args has been unpacked during the first print statement. 第二个打印不返回任何内容,因为args在第一个print语句中已解压缩。

Is there a way to maintain the content of a variable by still using the * feature? 有没有办法通过仍然使用*功能来维护变量的内容? Obviously, I can delegate (x for x in (a, b, c) if x is not None) into a dedicated function that I will call all the time. 显然, (x for x in (a, b, c) if x is not None) ,我可以委托(x for x in (a, b, c) if x is not None)到我将一直调用的专用函数中。 I was wondering if there was a simpler / more pythonic way to handle the operation. 我想知道是否有更简单/更pythonic的方式来处理操作。

You need to use [x for x in (a, b, c) if x is not None] (with square brackets) instead of (x for x in (a, b, c) if x is not None) . [x for x in (a, b, c) if x is not None]需要使用[x for x in (a, b, c) if x is not None] (带方括号)而不是(x for x in (a, b, c) if x is not None)

(...) creates a generator which becomes empty once iterated. (...)创建一个迭代后变为空的生成器。 Whereas [...] is the syntax of list comprehension which returns the list. [...]列表推导的语法,它返回列表。

For example: 例如:

>>> a = 1
>>> b = None
>>> c = None
>>> args = [x for x in (a, b, c) if x is not None]
>>> print(*args)
1
>>> print(*args)
1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM