可以帮助我迭代python
我有档案:
Sukirman 2011-07-01 09:53:43
Sukirman 2011-07-01 13:11:45
Sukirman 2011-07-01 16:36:03
Sukirman 2011-07-01 17:14:22
Sukirman 2011-07-04 12:16:40
Sukirman 2011-07-04 14:39:28
Sukirman 2011-07-04 15:32:13
Sukirman 2011-07-04 15:38:23
Sukirman 2011-07-04 16:11:23
Sukirman 2011-07-04 16:19:04
Sukirman 2011-07-05 09:26:08
Sukirman 2011-07-05 09:46:17
Sukirman 2011-07-05 14:08:44
Sukirman 2011-07-05 14:40:02
我想转换为列表
l = [("2011-07-01",("09:53:43","17:14:22")),
("2011-07-04",("12:16:40","16:19:04")),
"2011-07-05",("09:26:08","14:40:02"))]
任何人都可以用python帮助我
答案 0 :(得分:4)
您可能希望拥有字典而不是列表。否则,只需在下面的代码中填写d.items()
>>> import collections
>>> d = collections.defaultdict(list)
>>> for name, date, hour in (line.split() for line in open('the_file.txt')):
d[date].append(hour)
>>> print(d)
defaultdict(<class 'list'>,
{'2011-07-01': ['09:53:43', '13:11:45', '16:36:03', '17:14:22'],
'2011-07-05': ['09:26:08', '09:46:17', '14:08:44', '14:40:02'],
'2011-07-04': ['12:16:40', '14:39:28', '15:32:13', '15:38:23',
'16:11:23', '16:19:04']})
如果需要,您可以使用with
语句。
答案 1 :(得分:1)
是的,你最好使用disctionnaries 您必须使用正则表达式和组来制作列表,请尝试:
import re
regex=re.compile((?P<date>\d\d\d\d-\d\d-\d\d$).+(?P<hour>\d\d:\d\d:\d\d)$
l=regex.group()