python - How to fill up a matrix in Python using for loops
问题描述
How to add zeroes to the end of a list and fill a matrix with it? Currently I have
(1,0,1,1,0)
How to fill up a matrix such that it looks like this:
[[0, 0, 0],
[0, 1, 0],
[1, 1, 0]]
解决方案
In your question, you have clearly added the zeroes to the beginning of the matrix rather than the end but whatever.
To extend a list to one with 9 items with preceeding zeroes:
list_out = [0]*(9-len(list_in)) + list_in
to extend a list to one with 9 items with trailing zeroes just reverse the order:
list_out = list_in + [0]*(9-len(list_in))
We can convert a list with 9 items to a matrix using
matrix = [li[0:3,li[3:6],li[6:9]
so eg.
list_in = [1,2,3]
li = list_in + [0]*(9-len(list_in))
matrix = [li[0:3],li[3:6],li[6:9]]
gives
[[1, 2, 3], [0, 0, 0], [0, 0, 0]]
推荐阅读
- sql - MS Access Query,显示所有记录的条件
- php - 如何使用php下载大型mysql数据库
- node.js - ENOENT:没有这样的文件或目录:NODE JS
- python - 如何将我的数据框拆分为不同的数据框?
- powershell - 使用 Powershell 访问时,如何以编程方式防止来自 Outlook 的“可疑活动”对话框?
- gcc - 在 gcc-arm-none-eabi 中启用浮点仿真
- deep-learning - 如何将onedrive挂载到google colaboratory?
- javascript - 沿着 Promise 链传递价值
- postgresql - 返回 PostgreSQL 中更新值的变化
- ios - 无法在真实设备中安装项目