如何用增量步骤创建范围列表?

2024-06-28 06:53:08 发布

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

我知道可以创建一个一系列数字的列表:

list(range(0,20,1))
output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

但我想做的是在每次迭代中增加步骤:

list(range(0,20,1+incremental value)

递增时的p.e.=+1

expected output: [0, 1, 3, 6, 10, 15]  

这在python中可能吗?


Tags: 列表outputvalue步骤range数字listexpected
3条回答

尽管这个问题已经得到了答案,但我发现列表理解让这个问题变得非常简单。我需要与OP相同的结果,但是以24为增量,从-7开始到7。

lc = [n*24 for n in range(-7, 8)]

你可以这样做:

def incremental_range(start, stop, step, inc):
    value = start
    while value < stop:
        yield value
        value += step
        step += inc

list(incremental_range(0, 20, 1, 1))
[0, 1, 3, 6, 10, 15]

这是可能的,但不是通过range

def range_inc(start, stop, step, inc):
    i = start
    while i < stop:
        yield i
        i += step
        step += inc

相关问题 更多 >