Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python map function with multiple arguments to a list of tuples [duplicate]

The heading may sound bizarre but here is what I mean:

def f(x, y, z):
    return a_single_number_from_xyz
l = [(10, 'abc', 'def'), (20, 'efg', 'hij')]
print sum([ret_value_of_f_from_first_tuple, ret_value_of_f_from_second_tuple])

The three arguments of function f is the three elements of each of the tuple. Now, I want to apply function f to every tuple of list l and want to get the sum of those single numbers. How do I do that in a single statement? How do I map function and use list comprehension together here?

like image 694
QuestionEverything Avatar asked Dec 04 '22 21:12

QuestionEverything


2 Answers

In this particular case, I think you just want:

sum(n for n,_,_ in l)

But in general, you are looking for itertools.starmap, so

list(itertools.starmap(f, iterable)) 

is equivalent to

[f(*xs) for xs in iterable]

Hence the "star" map. Normally, I would just do:

sum(f(*xs) for xs in iterable)

For the general case, although:

sum(itertools.starmap(f, iterable))

Is similarly elegant to me.

like image 62
juanpa.arrivillaga Avatar answered Dec 06 '22 10:12

juanpa.arrivillaga


First let's make that an actual working function using all values, for example:

>>> def f(x, y, z):
        return x + len(y) + len(z)

Now your example data:

>>> l = [(10, 'abc', 'def'), (20, 'efg', 'hij')]

And one way to do it, giving map three iterables (one for each "column"):

>>> sum(map(f, *zip(*l)))
42

Lol. Didn't see that coming.

like image 24
Stefan Pochmann Avatar answered Dec 06 '22 11:12

Stefan Pochmann