在Python中,可以使用range函數(shù)生成等差數(shù)列。range函數(shù)的三個(gè)參數(shù)分別表示起始值、終止值和步長(zhǎng)。步長(zhǎng)參數(shù)默認(rèn)為1,可以省略。
以下是幾種生成等差數(shù)列的方法:
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]