如何将列表转换为逗号分隔元素的序列?

时间:2015-09-03 14:37:31

标签: python list python-3.x

想象一下,我将一些坐标作为元组列表给出:

coordinates = [('0','0','0'),('1','1','1')] 

我需要它是一个列表如下:

['XYZ', ['CO', 'X', '0', 'Y', '0', 'Z', '0'], ['CO', 'X', '1', 'Y', '1', 'Z', '1'],'ABC']

但我事先并不知道coordinates中有多少个元组,我需要动态创建列表。

首先,我使用循环创建没有'XYZ'的列表:

pointArray = []
for ii in range(0, len(coordinates)):
    pointArray.append(
        [
            "CO",
            "X"           , coordinates[ii][0],
            "Y"           , coordinates[ii][1],
            "Z"           , coordinates[ii][2]
        ])

然后我将'XYZ'添加到前面,'ABC'添加到结尾:

output = pointArray
output [0:0] = ["XYZ"]
output.append("ABC")

这给了我想要的输出。 但请将此视为一个例子。

我不是在寻找替代方法来追加,扩展,压缩或链接数组。

我真正想知道的是:是否有任何语法可以通过以下方式创建列表output

output = ["XYZ", pointArray[0], pointArray[1], "ABC"]

但动态?所以基本上我正在寻找像

这样的东西
output = ["XYZ", *pointArray, "ABC"]

似乎适用于像

这样的函数参数
print(*pointArray)

总结:如何将列表转换为逗号分隔元素序列?这是否可能?

PS:在Matlab中我只是习惯在单元格数组上使用冒号{:}来实现这一点。

背景

我正在使用包含上述列表的外部应用程序录制Python skripts。录制的脚本有时包含超过一百行代码,我需要缩短它们。最简单的方法是用预定义的循环创建列表替换looooong列表,并使用所需的语法扩展该数组。

3 个答案:

答案 0 :(得分:3)

你需要等到Python 3.5发布:

Python 3.5.0a4+ (default:a3f2b171b765, May 19 2015, 16:14:41) 
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> pointArray = [1, 2, 3]
>>> output = ["XYZ", *pointArray]
>>> output
['XYZ', 1, 2, 3]

在那之前,没有一般的方法:

Python 3.4.3 (default, Mar 26 2015, 22:03:40) 
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> pointArray = [1, 2, 3]
>>> output = ["XYZ", *pointArray]
  File "<stdin>", line 1
SyntaxError: can use starred expression only as assignment target

但是在有限的范围内,您可以使用+连接,这适用于您的示例:

>>> pointArray = [1, 2, 3]
>>> output = ["XYZ"] + pointArray
>>> output
['XYZ', 1, 2, 3]

*解包或.extend不同,这仅适用于相同类型的对象:

>>> pointArray = (1, 2, 3)
>>> output = ["XYZ"] + pointArray
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "tuple") to list
>>> output = ["XYZ"] + list(pointArray)
>>> output
['XYZ', 1, 2, 3]

答案 1 :(得分:1)

如何制作涉及zippingchaining的列表理解:

>>> from itertools import chain, izip
>>>
>>> coordinates = [('0','0','0'),('1','1','1')] 
>>> axis = ['X', 'Y', 'Z']
>>> ['XYZ'] + [['CO'] + list(chain(*izip(axis, item))) for item in coordinates]
['XYZ', ['CO', 'X', '0', 'Y', '0', 'Z', '0'], ['CO', 'X', '1', 'Y', '1', 'Z', '1']]

答案 2 :(得分:0)

import itertools

cmap = 'XYZABC'
coordinates = [('0','0','0'),('1','1','1')] 

result = [cmap[:3]] + [list(itertools.chain(*[('CO', cmap[i], x) if i == 0 else (cmap[i], x) for i, x in enumerate(coordinate)])) for coordinate in coordinates] + [cmap[3:]]
#['XYZ', ['CO', 'X', '0', 'Y', '0', 'Z', '0'], ['CO', 'X', '1', 'Y', '1', 'Z', '1'],'ABC']
相关问题