Python 如何以最简单的方式舍入特定函数的结果?
我已经创建了一个字典Python 如何以最简单的方式舍入特定函数的结果?,python,rounding,Python,Rounding,我已经创建了一个字典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]-yc
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)
这将完成您需要的操作,而无需转换为列表。您可以将其舍入,同时保存在dict中
这将完成您需要的操作,而无需转换为列表。您可以在保存dict本身时对其进行取整您可以使用嵌套列表:
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.]
您可以使用嵌套列表:
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.]