简体   繁体   中英

How to add 1 to every element of a matrix / nested list in Python?

I am currently working on a problem that requires me to take a matrix / nested list, and add 1 to every element of this list, and then return the new modified list. I also have to make it so that a user can input the matrix/nested list of their choice. For example, the person would enter: [[1,2,3],[4,5,6]] and the program would return [[2,3,4],[5,6,7]] So far I have this code:

m = int(input("Enter the number of rows: "))
matrice = []
i=0
while (i<m):
    print("Enter the row", i,"(separate each number by a space)")
    rang = [int(val) for val in input().split()]
    matrice.append(rang)
    i = i + 1
def add(a):
    res = []
    for i in range(len(a)):
        row=[]
        for j in range(len(a[0])):
            row.append(a[i][j]+1)
        res.append(row)
return res

This code works only for perfect matrices. My problem is, whenever the rows are not the same length, it gives me an error. For example if you were to enter the list [[1,2,3,4],[4,5,6]] it would not work. I was wondering how to proceed with doing this question. Also, I would prefer not to use numpy if possible. Thank you in advance for your help.

You can do this with list comprehensions very simply:

x = [[1,2,3,4],[4,5,6]]
[[z+1 for z in y] for y in x]
# [[2, 3, 4, 5], [5, 6, 7]]

However, if the "matrix" will be very large, I would encourage you to use a matrix object from numpy .

How about:

m = [[5, 7, 9, 3], [10, 8, 2, 9], [11, 14, 6, 5]]

m2 = [[v+1 for v in r] for r in m]

print m
print m2

Instead of using len(a[0]) use len(a[i]) it's the length of the current row

def add(a):
    res = []
    for i in range(len(a)):
        row=[]
        for j in range(len(a[i])):
            row.append(a[i][j]+1)
        res.append(row)
return res

And for any nested list of numbers:

test_data = [
    [1,2,3]
    ,[2,4]
    ,5
    ,[6,7,[8,9]]
    ]

import types
import numbers

def inc_el(list_or_num):
    if isinstance(list_or_num, numbers.Number):
        return list_or_num +1
    elif type(list_or_num) == types.ListType:
        return map(inc_el, list_or_num)

print map(inc_el, test_data)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM