Python list is converted into integer -


while testing code errors appeared - after mathematical operation, list 'shrinks' down itself's last item

in python 3.3 interpreter works fine...

a = [a + b a, b in zip(a, b)] 

i'm using code add list items

a = [1, 2, 3] b = [2, 3, 2] 

this works fine , returns

>>> [3, 5, 5] >>> b [2, 3, 2] 

then wrote class handle more lists:

class vector:      def __init__(self, name = '', vector = []):         self.__name = name         self.__vector = vector       def add_row_to_scalar_multiple(self, vector):         self.__vector = [self.__vector + vector.__vector self.__vector, vector.__vector in zip(self.__vector, vector.__vector)]       def __str__(self):         vec = ('{0} = {1}'.format(self.__name, self.__vector))         formatted_vec = vec.replace(',', '')         return formatted_vec 

when running code same lists above, 1 list reduced single integer

vec_a = vector('a', [1, 2, 3]) vec_b = vector('b', [2, 3, 2])   = [1, 2, 3] b = [2, 3, 2]  vec_b.add_row_to_scalar_multiple(vec_a)   = 3 b = [3, 5, 5] 

i can't figure out i'm doing wrong, please help??

a = [a + b a, b in zip(a, b)] 

you should not using "a, b" iteration variables, not same things original lists, , led make mistake of thinking should same things you're zipping.

it should example a = [aa + bb aa, bb in zip(a, b)]

and in converting class, have seen, instead of this:

self.__vector = [self.__vector + vector.__vector                  self.__vector, vector.__vector                  in zip(self.__vector, vector.__vector)] 

you should have this:

self.__vector = [aa + bb                  aa, bb                  in zip(self.__vector, vector.__vector)] 

also, function should probably called __iadd__, that's beside point.

on unrelated note:

   self.__vector = vector 

this line has 2 problems. 1 thing, it's storing reference list passed in (which may not want). bigger issue default vector = [] argument same list every time. mutable types defaults should avoided unless know you're doing. suggest self.__vector = list(vector).


Comments

Popular posts from this blog

java - JavaFX 2 slider labelFormatter not being used -

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -