Numpy中一个数组的多个索引列表

1 投票
1 回答
1378 浏览
提问于 2025-04-18 18:23

在正常情况下,包含整数的列表可以用作数组的索引。假设有这样一个列表:

arr = np.arange(10)*2
l = [1,2,5]
arr[l] # this gives np.array([2,4,10])

现在,我有多个索引列表,它们的长度各不相同,我想要从我的索引列表中的每个子列表中获取 arr[l]。我该如何做到这一点,而不使用逐个处理的方法(比如用 for 循环),或者更好的是,使用比 for 循环更快的方法,利用 numpy 呢?

举个例子:

lists = [[1,2,5], [5,6], [2,8,4]]
arr = np.arange(10)*2
result = np.array([[2,4,10], [10, 12], [4,16,8]]) #this is after the procedure I want to get

1 个回答

2

这要看你的列表有多大,才好判断这样做是否合理。一个方法是把所有列表合并在一起,然后进行切片操作,最后再把结果分配回列表中。

lists = [[1,2,5], [5,6], [2,8,4]]
arr = np.arange(10)*2

extracted = arr[np.concatenate(lists)]

indices = [0] + list(np.cumsum(map(len, lists)))
result = [extracted[indices[i]:indices[i + 1]] for i in range(len(lists))]

或者,考虑到@unutbu的评论:

result = np.split(extracted, indices[1:-1])

撰写回答