Home > database >  is there a way to return a list with other lists in it with this code?
is there a way to return a list with other lists in it with this code?

Time:11-03

I need to write this code where I take a list that has lists in it and takes in the ints in those lists and divide them by 2 and then return a new list that contains the lists with the divided ints

Here's what I came up with. I just can't seem to get a list that contains lists in it

def div_mat_by_scalar(mat, alpha):
    mat2=[]
    for i in range(len(mat)):
        for j in range(len(mat[i])):
            a = mat[i][j]//alpha
            mat2.append(a)
                
    return mat2 
mat1 = [[2, 4], [6, 8]]   
print(div_mat_by_scalar(mat1,2))

this prints [1,2,3,4] but I want [[1,2],[3,4]]

CodePudding user response:

You need to append to a nested list, not the main list.

def div_mat_by_scalar(mat, alpha):
    mat2=[]
    for row in mat:
        row2 = []
        for el in row:
            a = el//alpha
            row2.append(a)
        mat2.append(row2)
    return mat2

Or use list comprehensions:

def div_mat_by_scalar(mat, alpha):
    return [[el//alpha for el in row] for row in mat]

CodePudding user response:

You're appending every element to the list. Bamar's answer is great if your mat is always two dimensional, but if you want to generalize this function to any number dimensions, you may want to adopt a recursive approach:

def div_mat_by_scalar(mat, alpha):
    result = []
    for elem in mat:
        if isinstance(elem, list):
            result.append(div_mat_by_scalar(elem, alpha))
        else:
            result.append(elem // alpha)

    return result
  • Related