如何匹配给定的Python词典列表的词典元素?

时间:2017-01-28 04:31:52

标签: python dictionary

我有以下词典列表。我想根据开始和结束时间获得输出。如果两天或更多天具有相同的时间,则应将它们组合并显示,如输出中所示。

timings = [
    {'day': 'Monday', 'start': '8:00 am', 'close': '5:00 pm'},
    {'day': 'Tuesday', 'start': '7:00 am', 'close': '4:00 pm'},
    {'day': 'Wednesday', 'start': '7:00 am', 'close': '4:00 pm'},
    {'day': 'Thursday', 'start': '8:00 am', 'close': '5:00 pm'},
    {'day': 'Friday', 'start': '9:00 am', 'close': '4:00 pm'},
    {'day': 'Saturday', 'start': '9:00 am', 'close': '4:00 pm'},
    {'day': 'Sunday', 'start': '8:00 am', 'close': '5:00 pm'}
]

输出:

Monday            - 8:00 am - 5:00 pm

Tuesday-Wednesday - 7:00 am - 4:00 pm

Thursday          - 8:00 am - 5:00 pm

Friday-Saturday   - 9:00 am - 4:00 pm

Sunday            - 8:00 am - 5:00 pm

1 个答案:

答案 0 :(得分:4)

解决此问题的一个简单方法是使用itertools.groupby,例如:

>>> import itertools as it
>>> for (start, close), days in it.groupby(timings, lambda t: (t['start'], t['close'])):
...   print('{:20} - {} - {}'.format('-'.join(d['day'] for d in days), start, close))
Monday               - 8:00 am - 5:00 pm
Tuesday-Wednesday    - 7:00 am - 4:00 pm
Thursday             - 8:00 am - 5:00 pm
Friday-Saturday      - 9:00 am - 4:00 pm
Sunday               - 8:00 am - 5:00 pm