I have this code in perl that allows me to create a list of 8 to 1 and to create a numbering table.
the array is filled by adding to the list data (i.e. 8 to 1) before a "suffix" which is 1. i.e. inside the array we will have numrotation [1.8, 1.7, 1.6, 1.5, 1.4, 1.3, 1.2, 1.1]
. then fill the array with the values of 1 ..15
and 15.1 15.2 15.3
and 16..32
I would like to know which function can replace the push functions. I put you the code in perl and my test in python which did not : code in perl :
for ( reverse( 1 .. 8 ) ) { push @Numerotation, '1.' . $_ } push
@Numerotation, ( 1 .. 15, 15.1, 15.2, 15.3, 16 .. 31, 34 .. 45 );
code in python (does not work) :
import numpy as np
lst = list(range(1,8 1))
lst.reverse()
print(lst)
numerotation= np.array()
for i in lst :
d=1. i
numerotation.append(d)
print(numerotation)
CodePudding user response:
Since you are using numpy you can't do an append directly on the array like you can with regular Python lists. Instead you need to use the class function append()
. Also since np.array()
requires input you need to use np.empty(0)
to create an empty array.
import numpy as np
lst = list(range(1, 8 1))
lst.reverse()
print(lst)
numerotation = np.empty(0)
for i in lst :
d = "1." str(i)
numerotation = np.append(numerotation, d)
print(numerotation)
In your Perl code you create the floats as strings so I left them that way in this example. To make them numbers you need to convert them using float(d)
.
Here is another approach that uses a regular Python list and then creates a numpy array from it.
import numpy as np
lst = list(range(1, 8 1))
lst.reverse()
print(lst)
numbers = ["1." str(i) for i in lst]
numerotation = np.array(numbers)
print(numerotation)