如何转换';对于';使用python3循环到列表列表的矩阵表达式中?

如何转换';对于';使用python3循环到列表列表的矩阵表达式中?,python,numpy,matrix,Python,Numpy,Matrix,我需要将for循环转换为使用矩阵形式的表达式。我有一个列表列表、一个索引列表和一个名为“toSave”的形状矩阵(4,2): import numpy as np M = [list() for i in range(3)] indices= [1,1,0,1] toSave = np.array([[0, 0], [0, 1], [0, 2], [0, 3]]) 对于索引中的每

我需要将
for
循环转换为使用矩阵形式的表达式。我有一个列表列表、一个索引列表和一个名为“toSave”的形状矩阵(4,2):

import numpy as np

M = [list() for i in range(3)]
indices= [1,1,0,1]
toSave = np.array([[0, 0],
                   [0, 1],
                   [0, 2],
                   [0, 3]])
对于索引中的每个索引
i
,我希望保存与索引中的索引
i
位置对应的行:

for n, i in enumerate(indices):
    M[i].append(toSave[n])
结果是:

M=[[[0, 2]], [[0, 0], [0, 1], [0, 3]], []]
可以使用一个矩阵表达式来代替
for
循环,比如
M[index].append(toSave[range(4)])

这里有一种方法-

sidx = np.argsort(indices)
s_indx = np.take(indices, sidx)

split_idx = np.flatnonzero(s_indx[1:] != s_indx[:-1])+1
out = np.split(toSave[sidx], split_idx, axis=0)
样本运行-

# Given inputs
In [67]: M=[[] for i in range(3)]
    ...: indices= [1,1,0,1]
    ...: toSave=np.array([[0, 0],
    ...:        [0, 1],
    ...:        [0, 2],
    ...:        [0, 3]])
    ...: 

# Using loopy solution
In [68]: for n, i in enumerate(indices):
    ...:     M[i].append(toSave[n])
    ...:     

In [69]: M
Out[69]: [[array([0, 2])], [array([0, 0]), array([0, 1]), array([0, 3])], []]

# Using proposed solution
In [70]: out
Out[70]: 
[array([[0, 2]]), array([[0, 0],
        [0, 1],
        [0, 3]])]
性能提升

一个更快的方法是避免np.split,然后像这样使用-

sorted_toSave = toSave[sidx]
idx = np.concatenate(( [0], split_idx, [toSave.shape[0]] ))
out = [sorted_toSave[i:j] for i,j in zip(idx[:-1],idx[1:])]

索引在这里做什么?谢谢Divakar。我知道使用
切片
会更快,但我会尽量避免任何类型的
for
循环。只有一个问题:我如何用刚刚创建的矩阵更新以前的M列表:M不是空的,但等于我们最后计算的值的图像:
M=[[array([0,2]),[array([0,0]),array([0,1]),array([0,1]),array([0,3]),[]
,具有相同的索引和循环解决方案,我将得到
M=[[array([0,2]),array([0,2]),[array]),[array]([0,0])、数组([0,1])、数组([0,3])、数组([0,0])、数组([0,1])、数组([0,3])、[]
@GiuseppeAngora如果您试图更新已创建的
M
列表,请不要使用此方法。在使用for循环的问题上,由于每个索引处的子列表数量参差不齐,因此无法避免for循环。您只能使用“更好的循环”通过在进入循环之前做大多数事情,比其他人更有效地做事情。