如何创建具有增量步骤的范围列表?
How to create a list of a range with incremental step?
我知道可以创建一系列数字的列表:
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 中可行吗?
你可以这样做:
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
我进一步简化了上面的代码。认为这会成功。
List=list(range(1,20))
a=0
print "0"
for i in List:
a=a+i
print a
指定 nth
范围,为您提供具有特定模式的所有数字。
尽管这个问题已经得到解答,但我发现列表理解让这个问题变得非常简单。我需要与 OP 相同的结果,但以 24 为增量,从 -7 开始到 7。
lc = [n*24 for n in range(-7, 8)]
我知道可以创建一系列数字的列表:
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 中可行吗?
你可以这样做:
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
我进一步简化了上面的代码。认为这会成功。
List=list(range(1,20))
a=0
print "0"
for i in List:
a=a+i
print a
指定 nth
范围,为您提供具有特定模式的所有数字。
尽管这个问题已经得到解答,但我发现列表理解让这个问题变得非常简单。我需要与 OP 相同的结果,但以 24 为增量,从 -7 开始到 7。
lc = [n*24 for n in range(-7, 8)]