Reputation: 309
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 vector_partitions
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]])
print(pre_final)
However, I end up getting just the last element of whay my pre_final should be, so I end up getting only the vector [3,3,3]
. Does anyone know how I can fix this?
Upvotes: 0
Views: 168
Reputation: 61253
Actually you don't need to use range
or extend
to do this. Simply use list comprehensions.
>>> vector_partitions = [[4, 1, 1], [3, 2, 1], [2, 2, 2]]
>>> pre_final = [[6/i for i in item] for item in vector_partitions]
>>> pre_final
[[1.5, 6.0, 6.0], [2.0, 3.0, 6.0], [3.0, 3.0, 3.0]]
Upvotes: 1
Reputation: 11177
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]])
Upvotes: 1