简体   繁体   中英

How to substract multidimensional array in Python?

I have this multidimensional array:

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

I want to substract all of them with 1. So the result will be:

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

If you have a list of lists for sure, use a nested list comprehension:

In [13]: result = [[e-1 for e in i] for i in n]

In [14]: print result
[[0], [1], [2], [3], [4], [5], [6, 9], [7], [8], [6, 9]]
for x in n:
    for i, y in enumerate(x):
        x[i] = y - 1

This is more efficient, spacewise at least.

or if you want to use nested list comprehension like zhangxaochen did but assign it to the same value so it does it in place:

n[:] = [[b - 1 for b in a] for a in n]

Note that this actually still creates two extra lists so it has the same space complexity as assigning it to a new array.

result=n
for a in range(len(n)):
    for b in range(len(n[a])):
        result[a][b]=n[a][b]-1

Or you can use map() :

>>> import operator
>>> n = [[1], [2], [3], [4], [5], [6], [7, 10], [8], [9], [7, 10]]
>>> map(lambda x: map(lambda y: operator.sub(y, 1), x), n)
[[0], [1], [2], [3], [4], [5], [6, 9], [7], [8], [6, 9]]
def difference(a, n):
    try:
        return a - n
    except TypeError:
        return [difference(i, n) for i in a]

>>> difference([[1], [2], [3], [4], [5], [6], [7, 10], [8], [9], [7, 10]], 1)
[[0], [1], [2], [3], [4], [5], [6, 9], [7], [8], [6, 9]]
>>> difference([3, [1, 9, [1, 2, [3, 4, [5, 6]]]], [2], [[3, 4], [5, 6]], [3], [7, 10]], 1)
[2, [0, 8, [0, 1, [2, 3, [4, 5]]]], [1], [[2, 3], [4, 5]], [2], [6, 9]]

It works for all multidimensional lists.

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