简体   繁体   English

[Python]:对defaultdict的值进行排序

[英][Python]: sorting defaultdict's values

I want to sort values in defaultdict's item according to their time period. 我想根据其时间段对defaultdict项目中的值进行排序。 How can I sort them? 如何分类?

from collections import defaultdict
d = defaultdict(list)
d['Mon'].append("10:00-24:00")
d['Tue'].append("12:00-14:00")
d['Mon'].append("1:35-4:00")
for i in d.items():
    print i

if I do this above I would get: 如果我在上面这样做,我将得到:

('Mon', ['10:00-24:00', '1:35-4:00'])
('Tue', ['12:00-14:00'])

How can I sort the values in the defaultdict according to the time order, so I can have: 如何根据时间顺序对defaultdict中的值进行排序,因此我可以:

('Mon', ['1:35-4:00','10:00-24:00'])
('Tue', ['12:00-14:00'])

Sort the values as time ranges by time before printing them. 在打印之前,请按时间对这些值作为时间范围进行排序。 The following function converts your string to a tuple of two time objects: 以下函数将您的字符串转换为两个time对象的元组:

def str2timerange(timestring):
    timestring = timestring.replace("24:00", "00:00")
    return [datetime.time(*map(int, t.split(":"))) for t in timestring.split("-")]

Remember that "24:00" is not a valid time, it must be recorded as "00:00". 请记住,“ 24:00”不是有效时间,必须将其记录为“ 00:00”。

d = defaultdict(list)
d['Mon'].append("10:00-24:00") # WRONG, but str2timerange will fix it
d['Tue'].append("12:00-14:00")
d['Mon'].append("1:35-4:00")
for i in d.items():
    print(i[0],sorted(i[1],key=str2timerange))

#Mon ['1:35-4:00', '10:00-24:00']
#Tue ['12:00-14:00']

First your times should be in a format that is easier to sort. 首先,您的时间应该采用易于分类的格式。 As you have it now '10:00' is lexicographical smaller than '1:35' , which is not what you want. 现在,您拥有的'10:00'在字典上小于'1:35' ,这不是您想要的。 One way to fix this is to add leading zeros to times in the single-digit hours. 解决此问题的一种方法是在单位数小时的时间中添加前导零。

from collections import defaultdict
d = defaultdict(list)
d['Mon'].append("10:00-24:00")
d['Tue'].append("12:00-14:00")
d['Mon'].append("01:35-04:00")

for i in d.items(): i[1].sort()

>>> print d
defaultdict(<class 'list'>, {'Mon': ['01:35-04:00', '10:00-24:00'], 'Tue': ['12:00-14:00']})

If you need to convert your time strings automatically you could do a regex replace: 如果您需要自动转换时间字符串,可以执行正则表达式替换:

t = '1:35-4:00'
t = re.sub(r'(^|-)(\d:\d\d)', r'\g<1>0\2', t)
>>> print t
'01:35-04:00'

Also check out DYZ's solution which converts your strings to datetime tuples. 还请查看DYZ的解决方案,该解决方案将您的字符串转换为日期时间元组。 He also points out that '24:00' is not a valid time, and you could take care of those with t = t.replace('24:', '00:') . 他还指出,“ t = t.replace('24:', '00:') ”不是有效时间,您可以照顾那些t = t.replace('24:', '00:')

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

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