python - 如何在numpy数组中应用带有数组作为值的字典

标签 python numpy dictionary

我正在尝试映射这本字典

dict = {
5: np.array([1,1,1,1,1], dtype='int'),
4: np.array([1,1,1,1,0], dtype='int'),
3: np.array([1,1,1,0,0], dtype='int'),
2: np.array([1,1,0,0,0], dtype='int'),
1: np.array([1,0,0,0,0], dtype='int'),
0: np.array([0,0,0,0,0], dtype='int'),
-1: np.array([-1,0,0,0,0], dtype='int'),
-2: np.array([-1,-1,0,0,0], dtype='int'),
-3: np.array([-1,-1,-1,0,0], dtype='int'),
-4: np.array([-1,-1,-1,-1,0], dtype='int'),
-5: np.array([-1,-1,-1,-1,-1], dtype='int')}

在这个 numpy 数组中

target
array([[ 2,  0,  2,  0,  0,  3,  0,  0,  1,  0,  0, -2,  4, -2,  0,  0,
        -3, -3, -5,  1,  0,  0,  0,  2],
       [ 4,  4,  3,  2,  0,  0,  0,  1,  0,  0,  0,  0,  0,  0,  0,  0,
         1, -1, -2, -1, -2, -2, -3, -4],...])

numpy 数组上的元素是 int32。我如何映射它?

最佳答案

您可以使用列表理解并提供给 np.array:

res = np.array([list(map(d.__getitem__, row)) for row in target])

array([[[ 1,  1,  0,  0,  0],
        [ 0,  0,  0,  0,  0],
        [ 1,  1,  0,  0,  0],
        ...
        [ 0,  0,  0,  0,  0],
        [ 0,  0,  0,  0,  0],
        [ 1,  1,  0,  0,  0]],

       [[ 1,  1,  1,  1,  0],
        [ 1,  1,  1,  1,  0],
        [ 1,  1,  1,  0,  0],
        ...
        [-1, -1,  0,  0,  0],
        [-1, -1, -1,  0,  0],
        [-1, -1, -1, -1,  0]]])

请注意字典已重命名为 d:不要隐藏内置函数。

关于python - 如何在numpy数组中应用带有数组作为值的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52629221/

相关文章:

python - 为什么Python中的.format方法需要显式字符串转换?

python - 计算两个 Python 字典中包含的键的差异

python - 使用多处理或线程加速单个任务

python - 计算到多个点的最小距离的 map

python - 从列表中删除重复的子列表

python - 如何在Python中编辑以字典作为值的字典值?

c++ - 当我尝试使用读取和写入时,为什么 fstream 无法正常工作?

python turtle : How to use the write function to join an integer and a string with the integer coming from a list

python - 如何将Qt图形场景项保存在文件中并再次打开它?

python - python中的数组语句