在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]
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: python集合取值的方法是什么