我有一个这样的矩阵
[[1,2,4,6],
[4,7,9,9],
[1,9,10,20]]
我如何在python中按列获得部分总和?
[[1,2,4,6],
[(4-1),(7-2),(9-4),(9-6)],
[(1-4),(9-7),(10-9),(20-9)]]
从第二行开始,您想要的只是 rowi
和 row的区别i-1
,而第一行只是原始数组的第一行。最简单的方法是使用numpy。所以这有效:
In [1]: import numpy as np
In [2]: a = np.array( [[1,2,4,6],
...: [4,7,9,9],
...: [1,9,10,20]]
...: )
In [3]: np.vstack( (a[0], a[1:]-a[:-1]) )
Out[3]:
array([[ 1, 2, 4, 6],
[ 3, 5, 5, 3],
[-3, 2, 1, 11]])
正如亨利·沃顿勋爵 (!) 指出的那样,区别a[1:]-a[:-1]
与np.diff(a, axis=0)
.
如果您想要一个不涉及 numpy 的解决方案,并且只使用列表列表和itertools.tee
(内置),那么下面应该可以工作
from itertools import tee
a = [[1,2,4,6],
[4,7,9,9],
[1,9,10,20]]
b = []
b.append(a[0])
# Create two iterators and advance one once.
x, y = tee(a)
next(y)
# Iterate over your two iterators and construct a list t which is their difference
# then append this list to b
for i, j in zip(x, y):
t = [h-g for g, h in zip(i,j)]
b.append(t)
print(b)
# [[1, 2, 4, 6],
# [3, 5, 5, 3],
# [-3, 2, 1, 11]]
尝试
np.vstack((Z[0],np.diff(Z,axis=0)))
Z
您要区分的矩阵在哪里。
如果您不想使用numpy或itertools,这里是代码
>>> a=[[1,2,4,6],
... [4,7,9,9],
... [1,9,10,20]]
>>> a_r = a[::-1] # reverse original list
>>> for i in range(len(a_r)-1):
... for j in range(len(a_r[0])):
... a_r[i][j] = a_r[i][j] - a_r[i+1][j]
...
>>> a=a_r[::-1] # reverse result
>>> for i in a: print i
[1, 2, 4, 6]
[3, 5, 5, 3]
[-3, 2, 1, 11]
我觉得这个不错
>>> a = [[1,2,4,6],
... [4,7,9,9],
... [1,9,10,20]]
>>> c = [[0]*5] ; c.extend(a)
>>> print [[ s-r for r, s in zip(*t)] for t in zip(c[:-1],c[1:])]
[[1, 2, 4, 6], [3, 5, 5, 3], [-3, 2, 1, 11]]
>>>
在这里,我将一个零列表添加到列表列表(获取c
),并通过一些打包和解包使用zip
我有一个具有预期结果的列表列表。