Python Forum
creating a list from lists of lists
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
creating a list from lists of lists
#1
Can someone tell me how to sum values across lists of lists....For example I have a list of a list that is 2x4....It in turn is contained in a list that is 5 long so effectively a 2x4x5...I would like to grab the x element in each list from the whole 2x4x5...looking for the solution OTHER than numpy....Thank you...Here is the code for matrix list

Thank you!

#!/usr/bin/env python3 2 import random 3 def main(): 4 d = [] 5 for j in range(5): 6 d.append([[random.randint(0,4) for i in range(4)] for k in range(2)]) 7 return(d)
Reply
#2
Try not copy in line number in code.

So this is the start.
>>> lst = main() >>> lst [[[2, 1, 4, 3], [3, 4, 2, 1]], [[1, 0, 0, 3], [0, 3, 1, 1]], [[0, 1, 4, 2], [4, 0, 1, 3]], [[1, 0, 0, 4], [3, 3, 0, 0]], [[3, 1, 3, 0], [3, 4, 4, 2]]]
So to use eg sum() on the list need first to flatten the list out.
>>> for i in lst: ... lst = [item for n in i for item in n] ... print(lst) ... [2, 1, 3, 4, 1, 4, 3, 4] [4, 0, 1, 3, 0, 3, 0, 0] [0, 0, 0, 1, 2, 1, 4, 0] [2, 1, 0, 1, 4, 1, 4, 3] [4, 0, 3, 4, 1, 4, 2, 2]
Now will sum() work.
>>> lst = main() >>> for i in lst: ... lst = [item for n in i for item in n] ... print(sum(lst)) ... 17 18 13 12 15
Then i think you can do the last step if want the total sum.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with Lists Nevvieboy 8 1,093 Oct-20-2025, 07:59 AM
Last Post: Blablabla
  Extracting parts of paragraphs from word documents using python-docx library & lists Den0st 1 26,288 Oct-08-2025, 05:56 AM
Last Post: OtiliaGen
  Appending lists into lists from function is not working for me BoredBannana 2 2,066 Oct-25-2024, 05:18 PM
Last Post: deanhystad
  Nested Lists & Dictionaries Hudjefa 5 2,197 Sep-23-2024, 08:20 PM
Last Post: DeaD_EyE
Sad The issue with compare 2D lists przonak007 18 5,267 Jul-17-2024, 07:31 AM
Last Post: Pedroski55
  Compare lists w_i_k_i_d 6 2,433 May-23-2024, 07:23 PM
Last Post: deanhystad
Question Using Lists as Dictionary Values bfallert 8 3,889 Apr-21-2024, 06:55 AM
Last Post: Pedroski55
  problem with print lists MarekGwozdz 4 2,403 Dec-15-2023, 09:13 AM
Last Post: Pedroski55
  python convert multiple files to multiple lists MCL169 6 4,528 Nov-25-2023, 05:31 AM
Last Post: Iqratech
  Lists blake7 6 3,049 Oct-06-2023, 12:46 PM
Last Post: buran

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.