首页 > 解决方案 > 创建列表的三角形结构,其中包含左下角的数字

问题描述

我正在尝试创建一个看起来像这样的结构,它可以容纳的项目数为 n:

7
4 8
2 5 9
1 3 6 10

并将其转换为如下列表:

[[1, 3, 6, 10],[2, 5, 9],[4, 8],[7]]

我无法理解它,我认为每个项目都会增加1,然后2等等3,但我希望它们存储的方式是我无法弄清楚的。

fn(6)

[[1 3 6],[2 5],[4]]

标签: pythonlist

解决方案


我一定是有史以来最善良的人,但测试起来确实很有趣。这是一个有效的功能:

def fn(input):
    output = []

    # First row:
    row = [1]
    incrementor = 2
    while row[-1]+incrementor <= input:
        row.append(row[-1]+incrementor)
        incrementor += 1
    output.append(row)

    # Rest of rows:
    for i in range(len(output[0])-1):
        output.append([e-1 for e in output[-1][1:]])


print(fn(10))

>> [[1, 3, 6, 10], [2, 5, 9], [4, 8], [7]]

推荐阅读