Python Forum
addition for elements in lists of list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
addition for elements in lists of list
#1
Can someone please show me how to do the following addition? I have a matrix k
k = [[[4,3], [3,1], [2,0]], [[0,1], [1,2], [3,3]]]

I would like a result that adds the elements within each list (no numpy please)...Trying to learn and understand loops and iterations...Would like to see traditional loop and loop comprehension...

Result = [[7, 4, 2], [1, 3, 6]]

Thanks
Reply
#2
We aren't here to do the work for you, so what have you tried? Besides, problem solving is the most important skill to develop as you're learning to program.
Reply
#3
I figured it out using sum(row)....however it brings up a question ...below are two snippets of code that give me valid results...can you explain to me why I need c[0][i] for the case that uses append but not for the case where I use extend?? In the append case I tried taking one of the outer [] away and thought I could change the c[0][i] to c[i] but to no avail?? Like I said I both yield the same results with the exception that the append has what appears to be a four deep list of list and the extend is a 3 deep...

import random
def m():
    c = []; m = []
    c.extend([[[random.randint(0,4) for i in range(2)] for k in range(4)] for i in range(3)])
    for i in range(3):
        tmp = []
        for row in c[i]:
            tmp.append(sum(row))
        m.append(tmp)
    return(c,m)
import random
def m():
    c = []; m = []
    c.append([[[random.randint(0,4) for i in range(2)] for k in range(4)] for i in range(3)])
    for i in range(3):
        tmp = []
        for row in c[0][i]:
            tmp.append(sum(row))
        m.append(tmp)
    return(c,m)
Reply
#4
Python is programming language. One formulates ideas in spoken language and then translates them into Python. Can you spell it out - what is your idea how to reach objective?

If you really "Trying to learn and understand loops and iterations" then maybe following can help you.

We have matrix and want to sum sublists.

First of all (if we are not very good at reading squared brackets) we find out what is the structure of our matrix ('for every list in matrix print list/print every list in matrix'):

>>> matrix = [[[4,3], [3,1], [2,0]], [[0,1], [1,2], [3,3]]]
>>> for lst in matrix:     # 'for every list in matrix'
...     print(lst)         # 'display list'
...
[[4, 3], [3, 1], [2, 0]]
[[0, 1], [1, 2], [3, 3]]  
We can observe that we have two lists. We need to get 'into' sublists of said lists. For that we add another loop ('for every list in matrix print every sublist in list/print every sublist in list in matrix'):

>>> for lst in matrix:        # 'for every list in matrix'
...    for sublst in lst:     # 'for every sublist in list'
...        print(sublst)      # 'display sublist'
...                                                                        
[4, 3]
[3, 1]
[2, 0]
[0, 1]
[1, 2]
[3, 3]
We have 'reached' the needed sublists. But we actually don't want sublists themselves, we want sums. So we can instead sublists print out their sums:

>>> for lst in matrix:            # 'for every list in matrix
...    for sublst in lst:         # 'for every sublist in list
...        print(sum(sublst))     # 'display sum of sublist elements'
...                                                                        
7
4
2
1
3
6
We have needed data, but not in needed datastructure. We have to construct one. We need 'for every list in matrix have list of sums of sublists'. We translate it into Python:

>>> result = []
>>> for lst in matrix: 
...    result.append([])                  # 'for every list in matrix have list in results'
...    for sublst in lst:                 # 'for every sublist in list'
...        result[-1].append(sum(sublst)) # 'append sum of sublist to last list in results'
...                                                                        
>>> result                                                                 
[[7, 4, 2], [1, 3, 6]]
Using list comprehension this can be expressed as oneliner:

>>> [[sum(sublst) for sublst in lst] for lst in matrix]                     
[[7, 4, 2], [1, 3, 6]]
I suggest to have a articulated plan and then translate it into Python step by step.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  unable to remove all elements from list based on a condition sg_python 3 377 Jan-27-2024, 04:03 PM
Last Post: deanhystad
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 427 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  List all possibilities of a nested-list by flattened lists sparkt 1 878 Feb-23-2023, 02:21 PM
Last Post: sparkt
  Multiply and Addition in the same loop statement with logic. joelraj 2 1,000 Feb-02-2023, 04:33 AM
Last Post: deanhystad
  Checking if a string contains all or any elements of a list k1llcod3 1 1,023 Jan-29-2023, 04:34 AM
Last Post: deanhystad
  user input values into list of lists tauros73 3 1,025 Dec-29-2022, 05:54 PM
Last Post: deanhystad
  returning a List of Lists nafshar 3 1,015 Oct-28-2022, 06:28 PM
Last Post: deanhystad
  Creating list of lists, with objects from lists sgrinderud 7 1,565 Oct-01-2022, 07:15 PM
Last Post: Skaperen
  How to change the datatype of list elements? mHosseinDS86 9 1,912 Aug-24-2022, 05:26 PM
Last Post: deanhystad
  ValueError: Length mismatch: Expected axis has 8 elements, new values have 1 elements ilknurg 1 5,014 May-17-2022, 11:38 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

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