calculation on lists

Discussion in 'Python' started by loïc Lauréote, Dec 19, 2012.

  1. Thank for your answer,

    I found something allowing to avoid loops.
    I use operator overloading.


    import math

    class Vector:
    def __init__(self, x=0, y=0):
    self.x=x
    self.y=y
    def __eq__(self, vB): return (self.x==vB.x) and (self.y==vB.y)
    def __add__(self, vB): return Vector(self.x+vB.x,self.y+vB.y)
    def __sub__(self, vB): return Vector(self.x-vB.x,self.y-vB.y)
    def __mul__(self, c):
    if isinstance(c,Vector): return Vector(self.x*c.x,self.y*c.y)
    else: return Vector(c*self.x,c*self.y)


    def __div__(self, c):
    if isinstance(c,Vector): return Vector(self.x/c.x,self.y/c.y)
    else: return Vector(c*self.x,c*self.y)



    a = Vector(4,5)
    b = Vector(6,7)
    print a,b
    print b*b+a


    thx


    > Date: Wed, 19 Dec 2012 13:38:28 +0100
    > Subject: Re: calculation on lists
    > From:
    > To:
    > CC:
    >
    > 2012/12/19 loïc Lauréote <>:
    > hi,
    > I
    > have a question,
    > is there a tool to calculate on list ?
    >
    > something like :
    >
    > >a= [1,1,1,1]
    > >b = [5,9,8,4]
    > >c = a+b*a
    > >print c
    > >[6,10,9,5]

    >
    > Thx
    >
    > ======
    >
    > Hi,
    > for such simpler cases, you may try list comprehensions and probably
    > the zip(...) function
    >
    > >>> [a+b*a for a,b in zip([1,1,1,1], [5,9,8,4])]

    > [6, 10, 9, 5]
    > >>>

    >
    > hth,
    > vbr
    loïc Lauréote, Dec 19, 2012
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. =?UTF-8?B?w4FuZ2VsIEd1dGnDqXJyZXogUm9kcsOtZ3Vleg==

    List of lists of lists of lists...

    =?UTF-8?B?w4FuZ2VsIEd1dGnDqXJyZXogUm9kcsOtZ3Vleg==, May 8, 2006, in forum: Python
    Replies:
    5
    Views:
    384
    =?UTF-8?B?w4FuZ2VsIEd1dGnDqXJyZXogUm9kcsOtZ3Vleg==
    May 15, 2006
  2. loïc Lauréote

    calculation on lists

    loïc Lauréote, Dec 19, 2012, in forum: Python
    Replies:
    0
    Views:
    93
    loïc Lauréote
    Dec 19, 2012
  3. Vlastimil Brom

    Re: calculation on lists

    Vlastimil Brom, Dec 19, 2012, in forum: Python
    Replies:
    0
    Views:
    93
    Vlastimil Brom
    Dec 19, 2012
  4. Vlastimil Brom

    Re: calculation on lists

    Vlastimil Brom, Dec 19, 2012, in forum: Python
    Replies:
    0
    Views:
    110
    Vlastimil Brom
    Dec 19, 2012
  5. Tim Chase

    Re: calculation on lists

    Tim Chase, Dec 19, 2012, in forum: Python
    Replies:
    0
    Views:
    110
    Tim Chase
    Dec 19, 2012
Loading...

Share This Page