list comprehension question

rusi rustompmody at gmail.com
Wed Oct 17 03:13:57 EDT 2012


On Oct 17, 10:22 am, Terry Reedy <tjre... at udel.edu> wrote:
> On 10/16/2012 9:54 PM, Kevin Anthony wrote:
>
> > I've been teaching myself list comprehension, and i've run across
> > something i'm not able to convert.
>
> list comprehensions specifically abbreviate the code that they are
> (essentially) equivalent to.
>
> res = []
> for item in source:
>    res.append(f(item))
> res
>
> <==>
>
> [f(item) for item in source]
>
> Matrix multiplication does not fit the pattern above. The reduction is
> number addition rather than list appending.

Dunno why you say that. Heres matrix multiply using list
comprehensions:

from operator import add
def dot(p,q): return reduce(add, (x*y for x,y in zip(p,q)))

def transpose(m): return zip(*m)

def mm(a,b): return mmt(a, transpose(b))

def mmt(a,b): return [[dot(ra, rb) for rb in b] for ra in a]

which can then be 'reduced' to a one-liner if that takes your fancy



More information about the Python-list mailing list