Python 基于另一个列表对列表元素进行分组
我有两个列表:Python 基于另一个列表对列表元素进行分组,python,arrays,numpy,Python,Arrays,Numpy,我有两个列表:inp和base 我想根据base中的位置,将inp中的每个项目添加到out中的列表中 以下代码可以正常工作: from pprint import pprint as print num = 3 out = [[] for i in range(num)] inp = [[1,1],[2,1],[3,2],[7,11],[9,99],[0,-1]] base = [0,1,0,2,0,1] for i, num in enumerate(base): out[num]
inp
和base
我想根据base
中的位置,将inp
中的每个项目添加到out
中的列表中
以下代码可以正常工作:
from pprint import pprint as print
num = 3
out = [[] for i in range(num)]
inp = [[1,1],[2,1],[3,2],[7,11],[9,99],[0,-1]]
base = [0,1,0,2,0,1]
for i, num in enumerate(base):
out[num].append(inp[i])
print(out,width=40)
[[[1, 1], [3, 2], [9, 99]],
[[2, 1], [0, -1]],
[[7, 11]]]
我想使用NumPy
模块(np.array
和np.append
等)来完成这项工作
有人能帮我吗?假设
base
和inp
都是NumPy数组,我们可以这样做-
# Get sorted indices for base
sidx = base.argsort()
# Get where the sorted version of base changes groups
split_idx = np.flatnonzero(np.diff(base[sidx])>0)+1
# OR np.unique(base[sidx],return_index=True)[1][1:]
# Finally sort inp based on the sorted indices and split based on split_idx
out = np.split(inp[sidx], split_idx)
为了使其适用于列表,我们需要进行一些调整,主要是索引部分,我们可以使用
np。使用将索引替换为前面方法中列出的数组。因此,修改后的版本将是-
sidx = np.argsort(base)
split_idx = np.flatnonzero(np.diff(np.take(base,sidx))>0)+1
out = np.split(np.take(inp,sidx,axis=0), split_idx)