Lists aggregation

Peter Otten __peter__ at web.de
Tue Mar 17 03:18:08 EDT 2009


Mensanator wrote:

> 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)].

The point of my post was that you don't have to calculate that list of
tuples explicitly.

If you read the original post again you'll find that Mattia wanted that list
only as an intermediate step to something else. He gave "the exp of values"
as an example. As math.exp() only takes one argument I took this to
mean "exponentiation", or **/pow() in Python.

Peter



More information about the Python-list mailing list