我有个问题 我有一个名为(plane)的字典,在那里我可以调用“name”或“speed”等变量
这些价值观给我这种输出,例如:
print(plane.get('name'))
print(plane.get('altitude'))
输出:
'name'= FLRDD8EFC
'speed'= 136.054323
我的问题是,我怎样才能估计这些值如下所示
'name'= DD8EFC (Always deleting the first three lines)
'speed'= 136. (Approximate whole)
非常感谢你的帮助! 克
您可以,可能是,子类
collections.UserDict
(或者可能是@abamert建议的dict
),并在特殊方法__getitem__
中编写某种开关/过滤器/格式化程序:可能是这样的:
输出:
或子类化
dict
:免责声明:这更像是一个概念证明,而不是任何东西;我不推荐这种方法;这个“开关”很难看,一旦约束列表增加一点,它就可能失控
必须显式地编写代码
取出字符串,然后切片:
但是,使用
get
而不是[]
这一事实意味着您希望处理name
在plane
中不存在的可能性如果这是不可能的,您应该使用
[]
:如果是,则需要提供可以切片的默认值:
看起来您想舍入到0个小数位数,但要保留一个
float
?用0
数字调用round
。同样,您不需要get
,或者需要一个不同的默认值:…或:
至于打印:Python不喜欢在
float
之后打印.
,而不打印任何小数。您可以使用format
字段进行monkey操作,但手动将.
放入可能更简单:相关问题 更多 >
编程相关推荐