python列表到日期为键的字典

时间:2013-04-13 20:26:55

标签: python list dictionary

我正在尝试使用日期作为键和连续项作为其值来从此列表创建字典。

lst = ['Thu Apr 04', ' Weigh In', 'Sat Apr 06', ' Collect NIC', ' Finish PTI Video', 'Wed Apr 10', ' Serum uric acid test', 'Sat Apr 13', ' 1:00pm', 'Get flag from dhariwal', 'Sun Apr 14', ' Louis CK Oh My God', ' 4:00pm', 'UPS Guy']

dict = {}

for item in lst:
    if item.startswith(('Mon','Tue','____Wed','Thu','Fri','Sat','Sun'__))__:
        dict[item] = []
        saveItem = item
    else:
        dict[saveItem].append(item.____strip())

继续给我语法错误。

P.S。不是我的代码

1 个答案:

答案 0 :(得分:2)

import itertools as IT

items = ['Thu Apr 04', ' Weigh In', 'Sat Apr 06', ' Collect NIC', ' Finish PTI Video', 'Wed Apr 10', ' Serum uric acid test', 'Sat Apr 13', ' 1:00pm', 'Get flag from dhariwal', 'Sun Apr 14', ' Louis CK Oh My God', ' 4:00pm', 'UPS Guy']

date_word = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')

def isdate(datestring):
    return any(datestring.startswith(d) for d in date_word)

items = (item.strip() for item in items)

data = (list(group) for key, group in IT.groupby(items, key=isdate))
for date, items in IT.izip(*[data]*2):
    print('{d} {i}'.format(d=date[0], i=items))

产量

Thu Apr 04 ['Weigh In']
Sat Apr 06 ['Collect NIC', 'Finish PTI Video']
Wed Apr 10 ['Serum uric acid test']
Sat Apr 13 ['1:00pm', 'Get flag from dhariwal']
Sun Apr 14 ['Louis CK Oh My God', '4:00pm', 'UPS Guy']

  • 您可以使用IT.groupby根据需要对项目进行分组。

  • 如果您不将项目转储到dict中,则可以保留项目的显示顺序。

  • 您可以使用zip(*[iterator]*2) grouper recipe成对分组。

  • 避免使用像dict这样的变量名,因为它们会影响Python内置 同名的对象。