在 python 列表理解中解包元组(不能使用 *-operator)
问题描述
我正在尝试基于另一个列表创建一个列表,相同的值连续重复 3 次.
I am trying to create a list based on another list, with the same values repeated 3 times consecutively.
目前,我正在使用:
>>> my_list = [ 1, 2 ]
>>> three_times = []
>>> for i in range( len( my_list ) ):
... for j in range( 3 ):
... three_times.append( my_list[ i ] )
...
>>> print three_times
[1, 1, 1, 2, 2, 2]
但我想用更 Pythonic 的方式来做,比如:
But I would like to do it using a more Pythonic way, such as:
>>> my_list = [ 1, 2 ]
>>> three_times = []
>>> three_times = [ (value,) * 3 for value in my_list ]
>>> print three_times
[(1, 1, 1), (2, 2, 2)]
但是,我找不到解包元组的方法.
However, I cannot find a way to unpack the tuples.
像 three_times = [ *( (value,) * 3 ) for value in my_list ]
这样的东西非常适合解压元组,但这不是正确的语法.
Something like three_times = [ *( (value,) * 3 ) for value in my_list ]
would be perfect for unpacking the tuples but this is not a correct syntax.
解决方案
您不能在列表推导中使用 *
可迭代解包,该语法仅在调用中可用,并且在 Python 3 中,使用作业时.
You can't use *
iterable unpacking in a list comprehension, that syntax is only available in calls, and in Python 3, when using assignments.
如果你想使用列表推导,只需将你的 for
循环串联起来;您确实想直接访问 my_list
中的值,而不是生成索引:
If you want to use a list comprehension, just put your for
loops in series; you do want to access the values from my_list
directly rather than generate indices though:
[v for v in my_list for _ in range(3)]
相关文章