首页 > 解决方案 > 如何将带有元组 (x, y) 键的字典转换为矩阵或列表列表

问题描述

我想将字典转换为矩阵,但这与我见过的其他问题不同的是字典有一个 x 和 y 坐标的元组作为键。感谢您对此的帮助。我正在使用一个需要列表的新 python 包,但我的所有数据都在字典中。

test_dict = {
 (0, 0): 11,
 (0, 1): 13,
 (0, 2): 33,
 (1, 0): 24,
 (1, 1): 20,
 (1, 2): 4
}

[[11, 13, 33], [24, 20, 4]]

i.e.

test_list = [[11, 13, 33],
             [24, 20, 4]]
test_list

标签: python

解决方案


def dict_to_matrix(the_dict: dict) -> list:
    # Number of rows and columns in the matrix
    nrows = max(key[0] for key in the_dict) + 1
    ncols = max(key[1] for key in the_dict) + 1

    # Initialize the matrix (can use `numpy.empty` here)
    the_matrix = [[None]*ncols for _ in range(nrows)]

    # Fill the matrix
    for (i, j), the_matrix[i][j] in the_dict.items():
        ...

    # Could also do this,
    # but the loop above is more fun, IMO
    # for (i, j), value in the_dict.items():
    #    the_matrix[i][j] = value

    return the_matrix

test_dict = {
 (0, 0): 11,
 (0, 1): 13,
 (0, 2): 33,
 (1, 0): 24,
 (1, 1): 20,
 (1, 2): 4
}

print(dict_to_matrix(test_dict))

示例运行:

~/test $ python test.py 
[[11, 13, 33], [24, 20, 4]]

推荐阅读