What is not working with my "map" usage?
Peter Otten
__peter__ at web.de
Sat Sep 22 09:22:04 EDT 2018
Victor via Python-list wrote:
> Let me use a different input args and display them below. Basically, I am
> hoping to add up all elements of each nested list. So at first it should
> start with [1,11,111] ==> 1+11+111 = 123. But instead, it appears to take
> the 1st element from each nested list to add up [1,2,3] = 6. How should
> it be corrected? Thx.
I see three options. You can
(1) use a list comprehension
[add_all_elements(*sub) for sub in alist]
(2) replace map() with itertools.starmap()
list(itertools.starmap(add_all_elements, alist))
(3) change your function's signature from add_all_elements(*args) to
add_all_elements(args), either by modifying it directly or by wrapping it
into another function
list(map(lambda args: add_all_elements(*args), alist))
(3a) My personal preference would be to change the signature and then use
the list comprehension
def add_all_elements(args): ...
[add_all_elements(sub) for sub in alist]
More information about the Python-list
mailing list