如何在数组中更改数组

时间:2019-03-31 19:54:18

标签: python python-3.x numpy

我使用数组并获得一维,如下所示

 a=[(2, 1, [[0, 3]]), (5, 2, [[0, 2], [2, 3]]), (8,    3, [[0, 0], [2, 1], [3, 2]]), (10, 1, [[1, 3]]), (12, 4, [[0, 1], [1, 0], [2, 2], [3, 0]]), (15, 3, [[1, 1], [2, 0], [3, 1]])]

如何将其更改为二维

b=[(2, 1, [[0, 3]])
(5, 2, [[0, 2], [2, 3]])
(8, 3, [[0, 0], [2, 1],[3, 2]]),
(12, 4, [[0, 1], [1, 0], [2, 2], [3, 0]])]

然后转换为另一种方式

c=[(2, 1, 03),(5, 2, 02, 23),(8, 3, 00, 21, 32),(12, 4, 01, 10, 22, 30)]

1 个答案:

答案 0 :(得分:1)

如果我复制粘贴您的a

In [899]: a=[(2, 1, [[0, 3]]), (5, 2, [[0, 2], [2, 3]]), (8,    3, [[0, 0], [2, 
     ...: 1], [3, 2]]), (10, 1, [[1, 3]]), (12, 4, [[0, 1], [1, 0], [2, 2], [3, 
     ...: 0]]), (15, 3, [[1, 1], [2, 0], [3, 1]])]

ipython将其漂亮地打印为:

In [900]: a                                                                     
Out[900]: 
[(2, 1, [[0, 3]]),
 (5, 2, [[0, 2], [2, 3]]),
 (8, 3, [[0, 0], [2, 1], [3, 2]]),
 (10, 1, [[1, 3]]),
 (12, 4, [[0, 1], [1, 0], [2, 2], [3, 0]]),
 (15, 3, [[1, 1], [2, 0], [3, 1]])]

普通的python解释器可能以相同的方式显示它,但这只是一个显示问题,而不是数据结构。

如果我定义一个接受内部元组之一并返回两个值的组合的函数:

In [901]: def comb(alist): 
     ...:     return str(alist[0])+str(alist[1]) 
     ...:               

我可以通过以下列表理解将其应用于您的列表:

In [903]: [(i,j,*[comb(x) for x in k]) for i,j,k in a]                          
Out[903]: 
[(2, 1, '03'),
 (5, 2, '02', '23'),
 (8, 3, '00', '21', '32'),
 (10, 1, '13'),
 (12, 4, '01', '10', '22', '30'),
 (15, 3, '11', '20', '31')]

您可以编写自己的comb函数。除引号外,这似乎最接近您的c。但是除了将其制成字符串之外,无法产生03