我有一个多维数组:
n = [[1], [2], [3], [4], [5], [6], [7, 10], [8], [9], [7, 10]]
我希望将它们全部减1。因此结果将是:
result = [[0], [1], [2], [3], [4], [5], [6, 9], [7], [8], [6, 9]]
我有一个多维数组:
n = [[1], [2], [3], [4], [5], [6], [7, 10], [8], [9], [7, 10]]
result = [[0], [1], [2], [3], [4], [5], [6, 9], [7], [8], [6, 9]]
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
至少从空间上来说,这更加高效。
或者如果你想像zhangxaochen一样使用嵌套列表推导式,但将其分配给相同的值,以便它可以原地完成:
n[:] = [[b - 1 for b in a] for a in n]
result=n
for a in range(len(n)):
for b in range(len(n[a])):
result[a][b]=n[a][b]-1
result=n
只是将其余部分与 n
赋值相同。你可能想要的是 result 应该是 n 的深拷贝,这将需要 result = [m[:] for m in n]
。 - lvcmap()
函数:>>> 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]]
它适用于所有多维列表。
np.array(n)
会返回一个dtype=object的数组,而不是int类型,因此np.array(n) - 1
会出现TypeError错误(如果它们的大小相同,则会得到正确的答案)。 - lvc