Bottom Page

• 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,102 Threads: 85 Joined: Sep 2016 Reputation: 311 Likes received: 1265 #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 Working with Lists TheJax 3 224 Jan-23-2020, 02:08 PM Last Post: TheJax Help with lists and class objects AlluminumFoil 15 386 Jan-15-2020, 07:32 PM Last Post: AlluminumFoil Creating a List with many variables in a simple way donnertrud 1 119 Jan-11-2020, 03:00 PM Last Post: Clunk_Head concatenating lists in a comprehension Skaperen 3 212 Jan-01-2020, 08:10 PM Last Post: ichabod801 Bulk Generating Cloze Deletions based on Tatoeba sentences and word frequency lists wizzie 10 376 Dec-23-2019, 12:16 PM Last Post: wizzie how to compare a list to a list of lists kevthew 1 143 Dec-22-2019, 11:43 AM Last Post: ibreeden Multiplex lists using zip Clunk_Head 12 298 Dec-02-2019, 07:23 PM Last Post: DeaD_EyE List Comprehension - Creating a list of the length of an item help paul41 2 230 Nov-18-2019, 10:21 AM Last Post: perfringo Extracting parts of paragraphs from word documents using python-docx library & lists Den0st 0 671 Nov-06-2019, 12:07 AM Last Post: Den0st combining lists in a dictionary Skaperen 9 286 Nov-04-2019, 05:28 PM Last Post: DeaD_EyE

Forum Jump:

Users browsing this thread: 1 Guest(s)