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

Mic*_*ael 4 python list generator python-3.x

使用*iterable解包操作符功能我想保留变量的内容,以便我可以在我的代码中的多个位置使用该变量.这是一个表达我想要的例子:

>>> a = 1
>>> b = None
>>> c = None
>>> args = (x for x in (a, b, c) if x is not None)
>>> print(*args)
>>> 1
>>> print(*args)
>>> 
Run Code Online (Sandbox Code Playgroud)

第二个打印返回任何内容,因为args在第一个print语句中已解压缩.

有没有办法通过仍然使用*功能来维护变量的内容?显然,我可以委托(x for x in (a, b, c) if x is not None)给我一直打电话的专用功能.我想知道是否有更简单/更pythonic的方式来处理操作.

Moi*_*dri 5

你需要使用[x for x in (a, b, c) if x is not None] (用方括号)代替(x for x in (a, b, c) if x is not None).

(...)创建一个迭代后变为空的生成器.而列表理解[...]的语法返回列表.

例如:

>>> 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
Run Code Online (Sandbox Code Playgroud)