Lists aggregation

Mensanator mensanator at aol.com
Mon Mar 16 21:11:16 CET 2009


On Mar 16, 1:40 pm, Peter Otten <__pete... at web.de> wrote:
> mattia wrote:
> > I have 2 lists, like:
> > l1 = [1,2,3]
> > l2 = [4,5]
> > now I want to obtain a this new list:
> > l = [(1,4),(1,5),(2,4),(2,5),(3,4),(3,5)]
> > Then I'll have to transform the values found in the new list.
> > Now, some ideas (apart from the double loop to aggregate each element of
> > l1 with each element of l2):
> > - I wanted to use the zip function, but the new list will not aggregate
> > (3,4) and (3,5)
> > - Once I've the new list, I'll apply a map function (e.g. the exp of the
> > values) to speed up the process
> > Some help?
>
> Why would you keep the intermediate list?
>
> With a list comprehension:
>
> >>> a = [1,2,3]
> >>> b = [4,5]
> >>> [x**y for x in a for y in b]
>
> [1, 1, 16, 32, 81, 243]
>
> With itertools:
>
> >>> from itertools import product, starmap
> >>> from operator import pow
> >>> list(starmap(pow, product(a, b)))
>
> [1, 1, 16, 32, 81, 243]

That looks nothing like [(1,4),(1,5),(2,4),(2,5),(3,4),(3,5)].

>
> Peter




More information about the Python-list mailing list