簡體   English   中英

如何生成具有固定數量元素、固定起始值和結束值但可變間隔長度的數字列表?

[英]How to generate a list of numbers with a fixed number of elements, fixed start and end values but variable interval lengths?

假設元素數量為 8,列表為[40,47,54,61,68,75,82,89] 如果元素個數為16那么列表區間可以修改,列表變為[40,43,47,50,54,57,61,64,66,68,71,75,78,82,85,89]

如果是我,我會使用 numpy

>>> import numpy as np
>>> np.linspace(40,89,8)
array([40., 47., 54., 61., 68., 75., 82., 89.])
>>> np.linspace(40,89,16)
array([40.        , 43.26666667, 46.53333333, 49.8       , 53.06666667,
       56.33333333, 59.6       , 62.86666667, 66.13333333, 69.4       ,
       72.66666667, 75.93333333, 79.2       , 82.46666667, 85.73333333,
       89.        ])

請注意,這在您的案例中是一個問題,因為看起來您特別想要整數。 你可以做

>>> np.linspace(40,89,16).astype(int)
array([40, 43, 46, 49, 53, 56, 59, 62, 66, 69, 72, 75, 79, 82, 85, 89])

但這會將數字向下舍入,無論它們與上面的 integer 有多接近。 相反,您可以使用

>>> np.round(np.linspace(40,89,16))
array([40., 43., 47., 50., 53., 56., 60., 63., 66., 69., 73., 76., 79.,
       82., 86., 89.])

這些仍然是花車,所以你可以做

>>> np.round(np.linspace(40,89,16)).astype(int)
array([40, 43, 47, 50, 53, 56, 60, 63, 66, 69, 73, 76, 79, 82, 86, 89])

如果您特別需要整數。 如果確實需要,您也可以將其轉換回列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM