2017-10-21 69 views
1

我想將下三角形轉換爲上三角形,以便行成爲列。我有以下列表清單:PYTHON:如何將行轉置爲三角形數組的列?

[[-1] 
[-2, -2] 
[-2, -1, -2] 
[-3, 0, -1, -3 
[-3, 2, 1, -1, -3] 
[-4, 4, 3, 1, -1, -4] 
[-4, 7, 6, 4, 2, -1, -4] 
[-5, 10, 9, 7, 5, 2, -1, -5] 
[-5, 14, 13, 11, 9, 6, 3, -1, -5] 
[-6, 18, 17, 15, 13, 10, 7, 3, -1, -6] 
[-6, 23, 22, 20, 18, 15, 12, 8, 4, -1, -6] 
[-7, 28, 27, 25, 23, 20, 17, 13, 9, 4, -1, -7] 
[-7, 34, 33, 31, 29, 26, 23, 19, 15, 10, 5, -1, -7] 
[-8, 40, 39, 37, 35, 32, 29, 25, 21, 16, 11, 5, -1, -8] 
[-8, 47, 46, 44, 42, 39, 36, 32, 28, 23, 18, 12, 6, -1, -8] 
[-9, 54, 53, 51, 49, 46, 43, 39, 35, 30, 25, 19, 13, 6, -1, -9] 
[-9, 62, 61, 59, 57, 54, 51, 47, 43, 38, 33, 27, 21, 14, 7, -1, -9] 
[-10, 70, 69, 67, 65, 62, 59, 55, 51, 46, 41, 35, 29, 22, 15, 7, -1, -10]] 

我是否需要用零填充行以便zip可以做到這一點?

+0

我看到很多列表。我沒有看到列表。你究竟擁有什麼? –

+0

@ Stefan Pochmann - 哎呀。我複製了原始列表的打印聲明。 – jnthn

回答

1

你,如果你使用itertools.zip_longest不必墊,它會做填充你的,但你必須過濾自己:

In [7]: data 
Out[7]: 
[[-1], 
[-2, -2], 
[-2, -1, -2], 
[-3, 0, -1, -3], 
[-3, 2, 1, -1, -3], 
[-4, 4, 3, 1, -1, -4], 
[-4, 7, 6, 4, 2, -1, -4], 
[-5, 10, 9, 7, 5, 2, -1, -5], 
[-5, 14, 13, 11, 9, 6, 3, -1, -5], 
[-6, 18, 17, 15, 13, 10, 7, 3, -1, -6], 
[-6, 23, 22, 20, 18, 15, 12, 8, 4, -1, -6], 
[-7, 28, 27, 25, 23, 20, 17, 13, 9, 4, -1, -7], 
[-7, 34, 33, 31, 29, 26, 23, 19, 15, 10, 5, -1, -7], 
[-8, 40, 39, 37, 35, 32, 29, 25, 21, 16, 11, 5, -1, -8], 
[-8, 47, 46, 44, 42, 39, 36, 32, 28, 23, 18, 12, 6, -1, -8], 
[-9, 54, 53, 51, 49, 46, 43, 39, 35, 30, 25, 19, 13, 6, -1, -9], 
[-9, 62, 61, 59, 57, 54, 51, 47, 43, 38, 33, 27, 21, 14, 7, -1, -9], 
[-10, 70, 69, 67, 65, 62, 59, 55, 51, 46, 41, 35, 29, 22, 15, 7, -1, -10]] 

In [8]: t = itertools.zip_longest(*data) 

In [9]: [[x for x in sub if x is not None] for sub in t] 
Out[9]: 
[[-1, -2, -2, -3, -3, -4, -4, -5, -5, -6, -6, -7, -7, -8, -8, -9, -9, -10], 
[-2, -1, 2, 4, 7, 10, 14, 18, 23, 28, 34, 40, 47, 54, 62, 70], 
[-2, -1, 1, 3, 6, 9, 13, 17, 22, 27, 33, 39, 46, 53, 61, 69], 
[-3, -1, 1, 4, 7, 11, 15, 20, 25, 31, 37, 44, 51, 59, 67], 
[-3, -1, 2, 5, 9, 13, 18, 23, 29, 35, 42, 49, 57, 65], 
[-4, -1, 2, 6, 10, 15, 20, 26, 32, 39, 46, 54, 62], 
[-4, -1, 3, 7, 12, 17, 23, 29, 36, 43, 51, 59], 
[-5, -1, 3, 8, 13, 19, 25, 32, 39, 47, 55], 
[-5, -1, 4, 9, 15, 21, 28, 35, 43, 51], 
[-6, -1, 4, 10, 16, 23, 30, 38, 46], 
[-6, -1, 5, 11, 18, 25, 33, 41], 
[-7, -1, 5, 12, 19, 27, 35], 
[-7, -1, 6, 13, 21, 29], 
[-8, -1, 6, 14, 22], 
[-8, -1, 7, 15], 
[-9, -1, 7], 
[-9, -1], 
[-10]] 
+0

也許這會更準確地說'zip_longest'爲你填充! –

+0

@AdamSmith true! –

+0

@ juanpa.arrivillaga非常感謝。 – jnthn