gpt4 book ai didi

PYTHON:如何使用三角形数组将行转置为列?

转载 作者:太空宇宙 更新时间:2023-11-03 14:36:56 25 4
gpt4 key购买 nike

我想将下三角形转换为上三角形,以便行变成列。我有以下列表:

[[-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 可以做到这一点吗?

最佳答案

如果您使用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]]

关于PYTHON:如何使用三角形数组将行转置为列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46867618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com