Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Unpacking nested lists
#1
Hey, I beleive it's a relatively simple quiestion although i didn't find any simple answer in Google.

I'd like to create a function that unpacks a list of lists and create a new list that sums up the variables which are in the same index.
For instance: [[1,1],[1,3]] ---> [2,4]

or [[1,1,1],[1,0,0],[0,0,100]] ---> [2,1,101]

Not suppose to be very complex.

Thanks!
Reply
#2
>>> foo = [[1,1],[1,3]] 
>>> [sum(item) for item in zip(*foo)]
[2, 4]
>>> foo = [[1,1,1],[1,0,0],[0,0,100]]
>>> [sum(item) for item in zip(*foo)]
[2, 1, 101]
an alternative to list comprehension is map
>>> foo = [[1,1,1],[1,0,0],[0,0,100]]
>>> list(map(sum, zip(*foo)))
[2, 1, 101]
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Unpacking a dict with * or ** msrk 4 915 Dec-02-2023, 11:50 PM
Last Post: msrk
  List all possibilities of a nested-list by flattened lists sparkt 1 878 Feb-23-2023, 02:21 PM
Last Post: sparkt
  iterate through the dict_values while unpacking the dictionary PeacockOpenminded 3 1,262 Jan-22-2023, 12:44 PM
Last Post: PeacockOpenminded
  Unpacking zip object Mark17 12 3,106 Mar-28-2022, 04:59 PM
Last Post: deanhystad
  unpacking list wardancer84 2 1,837 Sep-11-2021, 02:42 PM
Last Post: wardancer84
  unpacking tuple not working project_science 1 1,451 Jan-09-2021, 09:09 PM
Last Post: buran
  Unpacking a list Mark17 3 2,555 Dec-18-2020, 05:08 AM
Last Post: aajkaal
  Unpacking wheel files DavidTheGrockle 3 10,881 Dec-15-2020, 05:11 PM
Last Post: DavidTheGrockle
  Split dict of lists into smaller dicts of lists. pcs3rd 3 2,312 Sep-19-2020, 09:12 AM
Last Post: ibreeden
  Searching through Nested Dictionaries and Lists Dave_London 1 6,254 Jul-09-2020, 03:36 PM
Last Post: mrdominikku

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020