python - How to add a constant value to every element of a Numpy array but the diagonal elements?
问题描述
I need to finish defining the function below.
def add_val_to_non_diag(A, val):
pass
Here is what I want to happen:
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
add_val_to_non_diag(A, 1)
Output
[[1, 3, 4],
[5, 5, 7],
[8, 9, 9]]
解决方案
您可以将值添加到每个元素,然后从对角线中减去。
import numpy as np
def add_val_to_non_diag(A, v):
return A + v * (1 - np.eye(A.shape[0]))
A = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
add_val_to_non_diag(A, 1)
=> array([[1., 3., 4.],
[5., 5., 7.],
[8., 9., 9.]])
推荐阅读
- java - 如何验证 javax.mail.* 中使用的 TLS 版本;
- javascript - 如何初始化 Uint8Array?
- teamcity - TeamCity 将其元跑步者数据存储在哪里?
- java - 无法通过命令提示符窗口执行 testng.xml 文件
- alexa - 如何实现 Alexa 音频播放器提示
- tfs - 在 TFS 2015 中,对于失败的 VNext 构建,构建失败的步骤(构建任务)是否存储在 DB 中的任何位置
- angularjs - 在 AngularJS 中,是否每次都需要捕获?
- javascript - Foundation 6 - 使用不显示图像的 JavaScript 填充 img 标签数据交换
- solr - solr 的同一个集合中的不同分片是否可以有不同的模式?
- javascript - slideBy owlCarousel 不起作用