Home > Net >  How to generate a list of numbers with a fixed number of elements, fixed start and end values but va
How to generate a list of numbers with a fixed number of elements, fixed start and end values but va

Time:09-28

Suppose a number of elements are 8 and the list is [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].

CodePudding user response:

If it were me, I'd use 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. 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.

  • Related