修改列表中的元组

时间:2013-02-28 18:52:18

标签: python python-2.7

我输入的时间是这样的:

09:00 12:00
10:00 13:00
11:00 12:30
12:02 15:00
09:00 10:30

我正在尝试将其构建为元组列表,转换为分钟:

[(540, 720), (600, 780), (660, 750), (722, 900), (540, 630)]

我想要一种更干净,更Pythonic的转换方式。我目前有一种笨拙的方式:

def readline(): 
    return sys.stdin.readline().strip().split()

natimes = [tuple(readline()) for _ in xrange(linesofinput))]
for i, (a,b) in enumerate(natimes):
    c = int(a.split(':')[0])* 60 + int(a.split(':')[1])
    d = int(b.split(':')[0])* 60 + int(b.split(':')[1])
    natimes[i] = (c,d)

我不觉得我在这里正确使用Python。

4 个答案:

答案 0 :(得分:5)

使用功能:

def time_to_int(time):
    mins,secs = time.split(':')
    return int(mins)*60 + int(secs)

def line_to_tuple(line):
    return tuple(time_to_int(t) for t in line.split())

natimes = [line_to_tuple(line) for line in sys.stdin]

答案 1 :(得分:2)

避免重复str.split等昂贵的操作。以下是一个简单的答案:

>>> print(s)
09:00 12:00
10:00 13:00
11:00 12:30
12:02 15:00
09:00 10:30
>>> def to_minutes(s):
...     hour, min = map(int, s.split(":"))
...     return hour * 60 + min
... 
>>> to_minutes("12:30")
750
>>> res = []
>>> for i1, i2 in map(str.split, s.split("\n")):
...     res.append((to_minutes(i1), to_minutes(i2)))
... 
>>> res
[(540, 720), (600, 780), (660, 750), (722, 900), (540, 630)]

答案 2 :(得分:1)

这是另一种选择,使用正则表达式:

import re
regex = re.compile('\s*(\d\d):(\d\d)\s+(\d\d):(\d\d)\s*')
natimes = []

for line in sys.stdin.readline():
    m = regex.match(line)
    if m:
        natimes.append((int(m.group(1))*60 + int(m.group(2)),
                        int(m.group(3))*60 + int(m.group(4))))

答案 3 :(得分:0)

以下是我将如何做到这一点(但在本例中使用数据字符串):

data = """09:00 12:00
10:00 13:00
11:00 12:30
12:02 15:00
09:00 10:30
"""

def minutes(s):
    hr, min = s.split(":")
    return int(hr) * 60 + int(min)

rv = []
for line in data.splitlines(): # may also use readlines from a file object
    rv.append(tuple([minutes(s) for s in line.split()]))

rv
# OUT: [(540, 720), (600, 780), (660, 750), (722, 900), (540, 630)]