在 python 列表理解中解包元组(不能使用 *-operator)

Unpacking tuples in a python list comprehension (cannot use the *-operator)(在 python 列表理解中解包元组(不能使用 *-operator))
本文介绍了在 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)]

这篇关于在 python 列表理解中解包元组(不能使用 *-operator)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)