繁体   English   中英

按降序打印字典中的条目

[英]Printing entries in a dictionary in descending order

按降序打印字典中的条目,以便我可以根据示例查看它们

08:02 - 注册

08:45 - 医生检查

09:00 - 程序

09:15 - 医生检查

09:25 - 射线照相

10:30 - 验血

11:00 - 医生检查

11:30 - 出院

class Time():
    def __init__(self, hour, minutes):
        self.hour = hour
        self.minutes = minutes

    def __str__(self):
        return "%02d:%02d" % (self.hour, self.minutes)

    def __repr__(self):
        if self.minutes == 0:
            return 'Time({0},{1}0)'.format(self.hour, self.minutes)
        return 'Time({0},{1})'.format(self.hour, self.minutes)
    
class Event():
    def __init__(self, time, nameStattion):
        self.time = time
        self.nameStattion = nameStattion

    def __str__(self):
        return "{0}-{1}".format(self.time, self.nameStattion)

    def __repr__(self):
        return 'Event(Time(%d,%d),"%s")' % (self.time.hour, self.time.minutes, self.nameStattion)
    
class MedicalRecord():
    data = {}

    def __init__(self, name, id):
        self.name = name
        self.id = id

    def __repr__(self):
       return 'Event(Time(%d,%d),"%s")' % (self.time.hour, self.time.minutes, self.nameStattion)

    def add(self, time, station):
        self.data[time] = Event(Time(int(time[0:2]), int(time[3:5])), station)

    def view(self):
        #for i in range(len(self.data)):
            print(eval(repr(self.data)))

time1 = Time(8, 2)
time1
print(time1)
time2 = eval(repr(time1))
print(time2)
event1 = Event(time1, 'registration')
event1
event2 = eval(repr(event1))
print(event2)
record1 = MedicalRecord('David', 1)
record1.add('08:02', 'registration')
print(record1.data)
record1.add('09:15','doctor checkup')
record1.add('08:45','doctor checkup')
record1.add('09:00','procedure')
record1.add('11:00','doctor checkup')
record1.add('09:25','radiography')
record1.add('11:30','hospital discharge')
record1.add('10:30','blood test')
record1.view()

在我的示例中,它打印为一侧列表

您可能想使用 python sorted() function。 它将有一个关键参数,您可以传递一个返回时间的 function,python 将根据该参数对列表进行排序。 从那里您可能会得到一个升序列表,您只需执行 list.reverse() 即可使其降序。

编辑:实际排序允许您使用“反向”参数选择它是升序还是降序。 有关更多信息,请参阅排序链接。

def keyFunc(EventObj): return f'{EventObj.time}' 
sortedList = sorted(SomeEventList, key=keyFunc, reversed = True)
    def view(self):
        for key in sorted(self.data):
            print(key, '-', self.data[key])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM