简体   繁体   English

如何生成具有固定数量元素、固定起始值和结束值但可变间隔长度的数字列表?

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

Suppose a number of elements are 8 and the list is [40,47,54,61,68,75,82,89] .假设元素数量为 8,列表为[40,47,54,61,68,75,82,89] If the number of elements are 16 then the list intervals can be modified and the list becomes [40,43,47,50,54,57,61,64,66,68,71,75,78,82,85,89] .如果元素个数为16那么列表区间可以修改,列表变为[40,43,47,50,54,57,61,64,66,68,71,75,78,82,85,89]

If it were me, I'd use numpy如果是我,我会使用 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.        ])

Note this is an issue in your case, as it looks like you specifically want integers.请注意,这在您的案例中是一个问题,因为看起来您特别想要整数。 You can do你可以做

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

but this rounds the numbers down, regardless of how close to the integer above they are.但这会将数字向下舍入,无论它们与上面的 integer 有多接近。 Instead, you can use相反,您可以使用

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

These are still floats, so you could do这些仍然是花车,所以你可以做

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

if you specifically need integers.如果您特别需要整数。 You can convert this back to a list if you really need to, too.如果确实需要,您也可以将其转换回列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM