urpi urpi - 8 months ago 15
Python Question

Adding elements to a new created vector in python

I have a vector as follows

vector_partitions = [[4,1,1],[3,2,1],[2,2,2]].

I want to create a new vector by modifying
by dividing 6 by each element of each vector element in vector_partitions, so for instance my new vector should be
pre_final = [[1.5,6,6], [2,3,6], [3,3,3]]

The code I wrote for this is the following:

vector_partitions = part(int(x),int(y))

length = len(vector_partitions)

for i in range(0, length):
length_new_vect = len(vector_partitions[1])
pre_final = []
pre_final.extend([int(x)/p for p in vector_partitions[i]])


However, I end up getting just the last element of whay my pre_final should be, so I end up getting only the vector
. Does anyone know how I can fix this?


You are assign [] to pre_final in each iteration and replacing the inserted values. You have to initialize pre_final outside the loop. Also you are using extend that concatenates 2 lists. You need to use append to push the new list in the end of pre_final. This fix your initial code

pre_final = []
for i in range(len(vector_partitions)):
    pre_final.append([6.0 / x for x in vector_partitions[i]])