Bottom Page

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)
Quote
#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.
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  addition for elements in lists of list ridgerunnersjw 3 127 Sep-15-2019, 07:11 AM
Last Post: perfringo
  Checking 2 lists graham23s 2 199 Sep-01-2019, 01:41 AM
Last Post: DeaD_EyE
  Creating csv header from user-input list dvanommen 2 153 Aug-26-2019, 08:51 PM
Last Post: dvanommen
  coding help lists, loops, and if statement ilondire05 5 279 Jul-19-2019, 07:32 AM
Last Post: perfringo
  Why does this list of lists end up with the same values alehak 2 187 Jul-18-2019, 12:34 PM
Last Post: perfringo
  Store a python list of lists in a database to use for searches later on klllmmm 3 419 Jun-20-2019, 07:54 AM
Last Post: buran
  Printing lists acooper7 1 198 Jun-17-2019, 09:37 PM
Last Post: Yoriz
  Generate unique random numbers from different lists Takeshio 5 300 May-24-2019, 07:29 PM
Last Post: ichabod801
  Multiplying two lists to make an array pberrett 15 654 May-15-2019, 02:22 AM
Last Post: micseydel
  zip lists with condition 3Pinter 6 313 May-09-2019, 05:16 PM
Last Post: DeaD_EyE

Forum Jump:


Users browsing this thread: 1 Guest(s)