如何以最简单的方式舍入特定函数的结果?
How to round the results of a specific function in the easiest way?
我已经创建了一个字典 cij
,如下一个代码所示。我想将值四舍五入为最接近的整数。我已经按照我的方式完成了并且效果很好,但我想知道是否有另一种更快更短的方法。
更具体地说,我希望 hypot
函数的结果自动四舍五入,而不需要列出值然后四舍五入。有什么想法吗?
import numpy as np
N = [0,1,2]
xcf = [40, 50, 60]
ycf = [20, 100, 170 ]
cij = {(i,j): np.hypot(xcf[i]-xcf[j], ycf[i]-ycf[j]) for i in N for j in N }
F= list(cij.values())
rounded_cij= np.round(F)
print(rounded_cij)
cij = {(i,j): np.round(np.hypot(xcf[i]-xcf[j], ycf[i]-ycf[j])) for i in N for j in N }
这将执行您需要的操作,而无需转换为列表。您可以在保存字典本身的同时对其进行舍入
您可以使用嵌套列表理解:
import numpy as np
N = [0,1,2]
xcf = [40, 50, 60]
ycf = [20, 100, 170 ]
rounded_cij = np.round([np.hypot(xcf[i]-xcf[j],
ycf[i]-ycf[j])
for i in N
for j in N])
print(rounded_cij)
输出:
[ 0. 81. 151. 81. 0. 71. 151. 71. 0.]
我已经创建了一个字典 cij
,如下一个代码所示。我想将值四舍五入为最接近的整数。我已经按照我的方式完成了并且效果很好,但我想知道是否有另一种更快更短的方法。
更具体地说,我希望 hypot
函数的结果自动四舍五入,而不需要列出值然后四舍五入。有什么想法吗?
import numpy as np
N = [0,1,2]
xcf = [40, 50, 60]
ycf = [20, 100, 170 ]
cij = {(i,j): np.hypot(xcf[i]-xcf[j], ycf[i]-ycf[j]) for i in N for j in N }
F= list(cij.values())
rounded_cij= np.round(F)
print(rounded_cij)
cij = {(i,j): np.round(np.hypot(xcf[i]-xcf[j], ycf[i]-ycf[j])) for i in N for j in N }
这将执行您需要的操作,而无需转换为列表。您可以在保存字典本身的同时对其进行舍入
您可以使用嵌套列表理解:
import numpy as np
N = [0,1,2]
xcf = [40, 50, 60]
ycf = [20, 100, 170 ]
rounded_cij = np.round([np.hypot(xcf[i]-xcf[j],
ycf[i]-ycf[j])
for i in N
for j in N])
print(rounded_cij)
输出:
[ 0. 81. 151. 81. 0. 71. 151. 71. 0.]