dot operations
jm.suresh@no.spam.gmail.com
jm.suresh at gmail.com
Thu Jan 11 09:06:39 EST 2007
Paddy wrote:
> jm.suresh at no.spam.gmail.com wrote:
> > Hi,
> > Frequently I get to do like this:
> > a = (1, 2, 3, 4) # some dummy values
> > b = (4, 3, 2, 1)
> > import operator
> > c = map(operator.add, a, b)
> >
> > I am finding the last line not very readable especially when I combine
> > couple of such operations into one line. Is it possible to overload
> > operators, so that, I can use .+ for element wise addition, as,
> > c = a .+ b
> > which is much more readable.
> >
> > Similarly, I want to use .- , .*, ./ . Is it possible to do?
> >
> > thanks.
> >
> > -
> > Suresh
>
> List comprehensions?
>
> >>> a = (1, 2, 3, 4)
> >>> b = (4, 3, 2, 1)
> >>> import operator
> >>> c = map(operator.add, a, b)
> >>> c
> [5, 5, 5, 5]
> >>> c1 = [a1+b1 for a1,b1 in zip(a,b)]
> >>> c1
> [5, 5, 5, 5]
> >>>
>
I just found this from :
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/384122
class Infix(object):
def __init__(self, function):
self.function = function
def __ror__(self, other):
return Infix(lambda x, self=self, other=other:
self.function(other, x))
def __or__(self, other):
return self.function(other)
def __rlshift__(self, other):
return Infix(lambda x, self=self, other=other:
self.function(other, x))
def __rshift__(self, other):
return self.function(other)
def __call__(self, value1, value2):
return self.function(value1, value2)
import operator
dotplus = Infix(lambda x,y: map(operator.add, x, y))
a = range(4)
b = range(4)
c = a |dotplus| b
>
> - Paddy.
More information about the Python-list
mailing list