在Python中,可以使用range函数生成等差数列。range函数的三个参数分别表示起始值、终止值和步长。步长参数默认为1,可以省略。
以下是几种生成等差数列的方法:
start = 1
stop = 10
step = 2
sequence = list(range(start, stop, step))
print(sequence) # [1, 3, 5, 7, 9]
start = 1
stop = 10
step = 2
sequence = [start + i * step for i in range((stop - start) // step + 1)]
print(sequence) # [1, 3, 5, 7, 9]
import numpy as np
start = 1
stop = 10
step = 2
sequence = np.arange(start, stop, step)
print(sequence) # [1 3 5 7 9]