修改lis中的元组

2024-09-29 20:30:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我输入了这样的时间:

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)]

我想要一个更干净,更像Python的转化方式。我现在有个笨拙的方法:

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。你知道吗


Tags: 方法in列表forreadlinereturndefstdin
3条回答

避免重复像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)]

使用功能:

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]

下面是另一个选项,使用正则表达式:

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))))

相关问题 更多 >

    热门问题