2

我有这样的时间输入:

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

4 回答 4

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]
于 2013-02-28T19:01:27.017 回答
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)]
于 2013-02-28T19:02:32.290 回答
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))))
于 2013-02-28T19:13:02.390 回答
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)]
于 2013-02-28T19:07:17.623 回答