在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]