python - 如何将带有元组 (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
解决方案
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]]
推荐阅读
- node.js - 将日志发送到远程弹性堆栈实例
- python - 使用 python api 在谷歌驱动器中显示子文件夹
- swift - 在运行时更改 Swift 中文本字段的键盘类型
- javascript - 不同子域之间的 SSO/Auth(使用 PHP)?
- excel - 使用 awk 和 bash 将 Data.txt 转换为 data.csv
- prometheus - Prometheus:是否可以在 prometheus Web UI 中创建/配置警报组?
- java - 在 Spring @Query 中使用变量
- c# - 任何人都可以对我在执行 .net 控制台应用程序时收到的错误有所了解。(System.Runtime.InteropServices.COMException (0x80040111)
- css - 在 React 中覆盖 CSS
- python - 按月计算 Python 循环时间