numpy的。在特定索引处求和多维数组

时间:2016-11-15 22:40:09

标签: python numpy vectorization

我尝试使用numpy替换像此代码这样的代码,以实现矢量化的高效操作。

counter = 0
idxs = [1, 3]
lists = [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
for l in lists:
    for idx in idxs:
        counter += l[idx]

1 个答案:

答案 0 :(得分:1)

只需对数组求和:

idxs = [1, 3]
lists = [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
ary = np.array(lists)
counter = ary[:,idxs].sum()