繁体   English   中英

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

[英]How to transform a list to a sequence of its comma-separated elements?

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

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' ,在末尾附加了'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列表,然后使用所需的语法扩展该数组。

您需要等到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.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]

如何进行涉及压缩链接的列表理解:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM