python如何生成等差數(shù)列

小億
410
2023-11-30 15:50:55

在Python中,可以使用range函數(shù)生成等差數(shù)列。range函數(shù)的三個(gè)參數(shù)分別表示起始值、終止值和步長(zhǎng)。步長(zhǎng)參數(shù)默認(rèn)為1,可以省略。

以下是幾種生成等差數(shù)列的方法:

  1. 使用range函數(shù)生成等差數(shù)列,并將其轉(zhuǎn)換為列表:
start = 1
stop = 10
step = 2
sequence = list(range(start, stop, step))
print(sequence)  # [1, 3, 5, 7, 9]
  1. 使用列表推導(dǎo)式生成等差數(shù)列:
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]
  1. 使用NumPy庫(kù)生成等差數(shù)列:
import numpy as np

start = 1
stop = 10
step = 2
sequence = np.arange(start, stop, step)
print(sequence)  # [1 3 5 7 9]

0