gpt4 book ai didi

python - 用于规范化矩阵中的值的列表理解

转载 作者:行者123 更新时间:2023-12-01 03:56:38 24 4
gpt4 key购买 nike

我有一个值矩阵,例如:

matrix = [
[1,2,3],
[5,6,7]
]

我想对它们进行标准化,以便每一行的总和为一。使用如下方法非常简单:

result = []
for x in matrix:
curr_row = [z/sum(x) for z in x]
result.append(curr_row)

我想知道是否有办法通过列表理解来做到这一点。

我得到的最接近的是

结果 = [x/sum(y) for y in matrix for x in y]

但这会将所有内容折叠到一个列表中。

最佳答案

你就快到了。

from __future__ import division        # for Python2

results = [[item/sum(row) for item in row] for row in matrix] # a list of lists

print(results)
# Output
[[0.16666666666666666, 0.3333333333333333, 0.5], [0.2777777777777778, 0.3333333333333333, 0.3888888888888889]]

关于python - 用于规范化矩阵中的值的列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37352055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com