Unpacking tuples in a python list comprehension (cannot use the *-operator)

筅森魡賤 提交于 2019-12-20 18:33:05

问题


I am trying to create a list based on another list, with the same values repeated 3 times consecutively.

At the moment, I am using:

>>> 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]

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.

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.


回答1:


You can't use * iterable unpacking in a list comprehension, that syntax is only available in calls, and in Python 3, when using assignments.

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)]


来源:https://stackoverflow.com/questions/37279653/unpacking-tuples-in-a-python-list-comprehension-cannot-use-the-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!