Bottom Page

Thread Rating:
• 0 Vote(s) - 0 Average
• 1
• 2
• 3
• 4
• 5
 creating a list from lists of lists ridgerunnersjw Programmer named Tim Posts: 11 Threads: 7 Joined: Sep 2019 Reputation: 0 Likes received: 0 #1 Sep-13-2019, 04:31 PM 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)``` snippsat Posts: 4,286 Threads: 90 Joined: Sep 2016 Reputation: 336 Likes received: 1314 #2 Sep-13-2019, 05:22 PM 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. « Next Oldest | Next Newest »

Top Page

 Possibly Related Threads... Thread Author Replies Views Last Post Help! Lists bwdu 7 200 Apr-05-2020, 06:39 AM Last Post: perfringo creating a list of dictionaries from API calls AndrewEnglsh101 5 131 Apr-03-2020, 02:21 PM Last Post: AndrewEnglsh101 Add items from one list to list of lists PUP280 2 342 Mar-28-2020, 08:34 AM Last Post: PUP280 Lists union and intersecion arbiel 5 154 Mar-28-2020, 05:57 AM Last Post: buran Money conversion - problems with lists and .format function fatherted99 1 169 Mar-12-2020, 06:29 PM Last Post: ndc85430 Creating new list based on exact regex match in original list interjectdirector 1 113 Mar-08-2020, 09:30 PM Last Post: deanhystad Finding value in nested dictionaries with lists mart79 16 411 Mar-08-2020, 08:16 PM Last Post: ndc85430 Can't seem to figure out how to put all of the lists items from a loop into 1 list Cosmosso 4 356 Feb-21-2020, 02:40 PM Last Post: Cosmosso Working with Lists TheJax 3 258 Jan-23-2020, 02:08 PM Last Post: TheJax Help with lists and class objects AlluminumFoil 15 421 Jan-15-2020, 07:32 PM Last Post: AlluminumFoil

Forum Jump:

Users browsing this thread: 1 Guest(s)