python - 点和值到数组的字典

标签 python numpy dictionary matrix

我有一个坐标对和整数的字典。第一个问题是有些点是负面的。

{(0, 0): 1, (-1, -1): 2, (1, -1): 3, (1, 1): 4}

to 

+---+---+---+
| 0 | 0 | 4 |
+---+---+---+
| 0 | 1 | 0 |
+---+---+---+
| 2 | 0 | 3 |
+---+---+---+

我相信我必须调整所有对,使它们大于零,这样我才能将它们用作矩阵的行、列对。然后插入是下一个。我相信 python 只有嵌套列表而不是矩阵,所以我想要一个 numpy 数组。

最佳答案

使用纯 Python:

def solve(d):

    x_min, y_min = map(min, zip(*d))
    x_max, y_max = map(max, zip(*d)) 

    arr = [[0]*(x_max-x_min+1) for _ in xrange(y_max-y_min+1)]

    for i, y in enumerate(xrange(y_min, y_max+1)):
        for j, x in enumerate(xrange(x_min, x_max+1)):
            arr[i][j] = d.get((x, y), 0)
    return arr[::-1]

输出:

solve({(0, 0): 1, (-1, -1): 2, (1, -1): 3, (1, 1): 4})
Out[80]: 
[[0, 0, 4],
[0, 1, 0],
[2, 0, 3]]

solve({(0, 0): 1, (-1, -1): 2, (1, -1): 3, (1, 1): 4, (2, 2):30, (-3, -4):100})
Out[82]: 
[[0, 0, 0, 0, 0, 30],
 [0, 0, 0, 0, 4, 0],
 [0, 0, 0, 1, 0, 0],
 [0, 0, 2, 0, 3, 0],
 [0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0],
 [100, 0, 0, 0, 0, 0]]

关于python - 点和值到数组的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23313315/

相关文章:

python - 在Python中如何确定一个点是否在某个平行四边形内部?

python - 创建运算矩阵张量

python - Numpy 重复一行或一列

python - Pandas,结合来自 2 个数据帧和一本字典的信息

python - 根据标签更改颜色和大小(matplotlib,python 3)

python - 如何取消闹钟功能?

python - Mysql自动提交与查询缓存的关系

python - 不同的迭代器给我不同的答案

python - 计算从文件中读取异常时一行中第一个单词出现的次数

python - 将字符串转换为字典列表