MAJ
MAJ

Reputation: 497

add number to multidimensional array python

If I have a list like below:

t = [[221.0, 223.0, 43.4],[32.5, 56.7, 65.4, 54.6]]

How can I add a value to each number? For example, I want to add 1 to each number so the list would look like:

tt = [[222.0, 223.0, 44.4],[33.5, 57.7, 66.4, 55.6]]

Currently, I can write the code to replace the first list with the second list, but I would like to create a new list while keeping the first one as well. Thanks!

Upvotes: 1

Views: 661

Answers (2)

Mykola Zotko
Mykola Zotko

Reputation: 17794

You can create the partial function with the operator add(), which adds one to another number

from functools import partial
from operator import add

add_one = partial(add, 1)
print(add_one(1))
# 2
print(add_one(2))
# 3

and map the function add_one() to each element in the sublist.

t = [[221.0, 223.0, 43.4],[32.5, 56.7, 65.4, 54.6]]

tt = [list(map(add_one, i)) for i in t]
# [[222.0, 224.0, 44.4], [33.5, 57.7, 66.4, 55.6]]

Upvotes: 0

yatu
yatu

Reputation: 88226

Given that you're using lists, you can use the following nested list comprehension, which returns another nested list with 1 added to each number in the sublists:

[[j + 1 for j in i] for i in t]
[[222.0, 224.0, 44.4], [33.5, 57.7, 66.4, 55.6]]

So simply do:

t = [[221.0, 223.0, 43.4],[32.5, 56.7, 65.4, 54.6]]
tt = [[j + 1 for j in i] for i in t]

Upvotes: 3

Related Questions