生成一系列连续整数长度递增的列表

2024-09-30 22:22:41 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一个正整数n;print n-1列表,长度递增,由Python中的连续整数组成。你知道吗

例如:对于n=4,它应该打印列表(按顺序):

[[1], [2], [3], [4]], [[1, 2], [2, 3], [3, 4]], [[1, 2, 3], [2, 3, 4]]

我尝试了itertools中的各种选项,但没有成功。你知道吗

编辑这里有一个失败的attepmt,使用combinations

n = 4
from itertools import product, permutations, tee, combinations
for i in range(n):
    print list(combinations(range(1, n+1), r = i))

它打印出来了

[()]
[(1,), (2,), (3,), (4,)]
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]

这里的问题是(除了第一行中的空白列表),它在第三和第四行中打印更多的元素。你知道吗


Tags: fromimport编辑列表顺序选项range整数
2条回答

我认为你只需要循环和切片:

def increasingLengths(n):
    ret = []
    sample = [i + 1 for i in range(n)]
    for i in range(1, n):
        aList = []
        maxItems = n - i + 1
        for j in range(maxItems):
            aList.append(sample[j:j + i])
        ret.append(aList)
    return ret

print(increasingLengths(4))

输出:

[[[1], [2], [3], [4]], [[1, 2], [2, 3], [3, 4]], [[1, 2, 3], [2, 3, 4]]]

提供替代解决方案:

我将使用overlapping函数。我想有些人把它叫做window函数(?)。你知道吗

像这样:

from collections import deque

def overlapping(seq, n):
    result = deque(seq[:n], maxlen=n)
    yield tuple(result)
    for x in seq[n:]:
        result.append(x)
        yield tuple(result)

这将给你:

>>> list(overlapping('abcdefg', 3))
[('a', 'b', 'c'), ('b', 'c', 'd'), ('c', 'd', 'e'), ('d', 'e', 'f'), ('e', 'f', 'g')]

Peter Norvig has a lovely implementation of this.

用它做你想做的事情相当简单:

def increasing_lengths(n):
    seq = list(range(1, n + 1))
    for i in range(1, n):
        yield list(overlapping(seq, i))

>>> list(increasing_lengths(4))
[[(1,), (2,), (3,), (4,)], [(1, 2), (2, 3), (3, 4)], [(1, 2, 3), (2, 3, 4)]]

您也可以不用使用collections来实现这一点,但它不会这么短。你知道吗

给你,我的两分钱。你知道吗

相关问题 更多 >