【发布时间】:2021-10-17 04:04:34
【问题描述】:
我正在尝试从使用二维 numpy 创建的数组中实现到一组值的简单映射。
对于数组中的每一行,我需要选择与一组值对应的正确值并将其添加到数组中。
例如:
[0, 1, 0, 0] -> 3 ... [1, 0, 1, 0] -> 2
但是,由于我的数据集的大小,我的第一个实现让我怀疑我是否在做一些真正错误或根本没有效率的事情,所以我在没有使用 for 循环的情况下做了这个解决方法,并使用字典查找优化了速度执行。
import numpy as np
# function to perform the search and return the index accordingly (it is supposed to be fast because of data structure)
def get_val(n):
map_list = {0: [0, 1, 0], 1: [0, 1, 0], 2: [1, 0, 0], 3: [0, 0, 1]}
map_vals = list(map_list.values())
index = map_vals.index(list(n))
return(index)
# set of arbitrary arrays
li = np.array([[0, 1, 0], [0, 0, 1]])
# here is the performance improvement attempt with the help of the function above
arr = [get_val(n) for n in li]
print(arr)
我不完全确定这是否是获取此类集合所需值的正确方法。如果有更好的方法,请告诉我。
否则,我指的是我的主要问题:
- 优化代码的最佳方法是什么?
非常感谢您的帮助。
【问题讨论】:
-
只创建一次map_vals,不重复
-
好的,这很好。但是经过这个微不足道的修正之后,有什么办法可以优化速度呢?
标签: python performance numpy dictionary