-3

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

Jared Farrish
  • 48,585
  • 17
  • 95
  • 104
prapto
  • 15
  • 2

2 Answers2

4

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.

1

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()
kingz
  • 11
  • 2