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

僤鯓⒐⒋嵵緔 提交于 2021-01-29 04:32:05

问题


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.


回答1:


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.




回答2:


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



回答3:


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



回答4:


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)


来源:https://stackoverflow.com/questions/33769581/how-to-add-1-to-every-element-of-a-matrix-nested-list-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!