字典变量的逼近与修正

2024-09-29 23:27:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个问题 我有一个名为(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)

非常感谢你的帮助! 克


Tags: thenameget字典alwaysfirstthreespeed
3条回答
>>> plane.get('name')[3:]
'DD8EFC'
>>> round(plane.get('speed'))
136

您可以,可能是,子类collections.UserDict(或者可能是@abamert建议的dict),并在特殊方法__getitem__中编写某种开关/过滤器/格式化程序:

可能是这样的:

from collections import UserDict


class MyDict(UserDict):

    def __getitem__(self, key):
        if key == 'name':
            return self.data[key][3:]
        if key == 'speed':
            return round(self.data[key], 3)
        return self.data[key]


if __name__ == '__main__':

    mydata = MyDict({'name': 'ABCDEF', 'speed': 12.123456})
    print(mydata['name'], mydata['speed'])

输出:

DEF 12.123

或子类化dict

class MyDict(dict):

    def __getitem__(self, key):
        if key == 'name':
            return self.get(key)[3:]
        if key == 'speed':
            return round(self.get(key), 3)
        return self[key]

免责声明:这更像是一个概念证明,而不是任何东西;我不推荐这种方法;这个“开关”很难看,一旦约束列表增加一点,它就可能失控

My question is, how can I approximate the values ​​as follows?

必须显式地编写代码


'name'= DD8EFC (Always deleting the first three lines)

取出字符串,然后切片:

name = plane.get('name')[3:]
print(f"'name' = {name}'")

但是,使用get而不是[]这一事实意味着您希望处理nameplane中不存在的可能性

如果这是不可能的,您应该使用[]

name = plane['name'][3:]

如果,则需要提供可以切片的默认值:

name = plane.get('name', '')[3:]

'speed'= 136. (Approximate whole)

看起来您想舍入到0个小数位数,但要保留一个float?用0数字调用round。同样,您不需要get,或者需要一个不同的默认值:

speed = round(plane['speed'], 0)

…或:

speed = round(plane.get('speed', 0.0), 0)

至于打印:Python不喜欢在float之后打印.,而不打印任何小数。您可以使用format字段进行monkey操作,但手动将.放入可能更简单:

print(f"'speed': {speed}.")

相关问题 更多 >

    热门问题