time attendance [closed]
can help me with iterating with python
I have file:
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
I want to convert to list
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"))]
can anybody help me please with python
You may want to have a dictionary instead of a list. Otherwise just make d.items()
in the code below
>>> 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']})
you may use a with
statement if you want.
Yes you better use disctionnaries You have to use regular expressions and groups to make your list, try:
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()
精彩评论