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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With