python 实现矩阵填充0的例子

yipeiwu_com6年前Python基础

需求:

原矩阵

[[1 2 3]
 [4 5 6]
 [7 8 9]]

在原矩阵元素之间填充元素 0,得到

[[1. 0. 2. 0. 3.]
 [0. 0. 0. 0. 0.]
 [4. 0. 5. 0. 6.]
 [0. 0. 0. 0. 0.]
 [7. 0. 8. 0. 9.]]

思路:

先求出扩充矩阵的维度,再按照每一行每一列遍历,根据元素的索引规律依次赋值,最终实现新的扩充矩阵。这个思路实现如下:

import numpy as np

def PadMat(Ndim, Mat):
 Brow = Bcol = 2*Ndim-1
 B = np.zeros([Brow, Bcol])
 for row in range(Brow):
 if row%2 == 0:
 for col in range(Bcol):
 if col%2 == 0:
 pos_c = int(col/2)
 pos_r = int(row/2)
 # print(row, col)
 B[row, col] = Mat[pos_r, pos_c]
 else:
 B[row, col] = 0
 return B


# A = np.arange(9) + 1
# A = A.reshape([3, 3])
A = np.arange(16) + 1
A = A.reshape([4, 4])
# print(A.shape[0])
N = Arow = Acol = A.shape[0]

NewMat = PadMat(Ndim=N, Mat=A)
print(A)
print(NewMat)

总结:

这个思路很直接,但是循环套循环是一个很笨的办法,而且遍历也很慢。不知道网友有什么好的思路吗?

以上这篇python 实现矩阵填充0的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现处理逆波兰表达式示例

本文实例讲述了Python实现处理逆波兰表达式。分享给大家供大家参考,具体如下: 中文名: 逆波兰表达式 外文名: Reverse Polish Notation 别名: 后缀表达式 逆...

二种python发送邮件实例讲解(python发邮件附件可以使用email模块实现)

可以使用Python的email模块来实现带有附件的邮件的发送。 SMTP (Simple Mail Transfer Protocol)邮件传送代理 (Mail Transfer Ag...

python双向链表实现实例代码

python双向链表实现实例代码

示意图:python双向链表实现代码:#!/usr/bin/python # -*- coding: utf-8 -*- class&nbs...

python中使用urllib2获取http请求状态码的代码例子

采集内容常需要得到网页返回的验证码做进一步处理 下面代码是用python写的用来获取网页http状态码的脚本 #!/usr/bin/python # -*- coding: utf-...

django基于restframework的CBV封装详解

一.models数据库映射 from django.db import models # Create your models here. class Book(models.Mo...