以下代码的目的是返回输入直径的最小管道坡度。如果 DIA 输入(以米为单位)不在键值范围内,则代码将返回错误。
D_MINSLOPE = {100:60, 150:100, 225:300, 300:400, 375:550, 450:700, 525:750, 600:900, 675:1050, 750:1200, 825:1380, 900:1600, 1050:2000, 1200:2400, 1350:2800, 1500:3250, 1650:3700, 1800:4200}
def minslope(DIA):
DIA_mm = round(DIA * 1000)
Slope = 1/D_MINSLOPE[DIA_mm]
return Slope
我目前将按照 this answered question 使用 'try/except' 'if/elif' 来解决不同基数(50、75、150)的问题。
有没有一种更Pythonic的方法来四舍五入到键值?
我注意到这个问题类似于 linked这是关于数组的。
最佳答案
IIUC,以下相关示例 question ,您可以在字典中搜索最接近的key
。例如如果您想搜索 500
:
min(D_MINSLOPE, key=lambda x:abs(x-500))
将返回525
,它是字典
键中最接近的值。
因此,您可以尝试将功能更改为:
def minslope(DIA):
# convert Diameter (m) to Diameter (mm)
DIA_mm = DIA * 1000
# get closest value
DIA_cv = min(D_MINSLOPE, key=lambda x:abs(x-DIA_mm))
Slope = 1/D_MINSLOPE[DIA_cv]
return Slope
关于python - 舍入到 python 字典中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49765408/