Rem*_*man 5 python increment range python-3.x
我知道可以创建一系列数字列表:
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]
Run Code Online (Sandbox Code Playgroud)
但我想要做的是增加每次迭代的步骤:
list(range(0,20,1+incremental value)
Run Code Online (Sandbox Code Playgroud)
增量= +1时的pe
expected output: [0, 1, 3, 6, 10, 15]
Run Code Online (Sandbox Code Playgroud)
这在python中可能吗?
这是可能的,但不是range:
def range_inc(start, stop, step, inc):
i = start
while i < stop:
yield i
i += step
step += inc
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
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]
Run Code Online (Sandbox Code Playgroud)
尽管这个问题已经得到了回答,但我发现列表理解使这变得非常简单。我需要与 OP 相同的结果,但增量为 24,从 -7 开始一直到 7。
lc = [n*24 for n in range(-7, 8)]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5037 次 |
| 最近记录: |