-5

我试图从这个列表中创建一个字典,使用日期作为键,连续项作为它的值。

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())

一直给我语法错误。

PS不是我的代码

4

1 回答 1

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根据需要对项目进行分组。

  • 如果您不将项目转储到字典中,则可以保留项目出现的顺序。

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

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

于 2013-04-13T20:32:52.653 回答