1

我有这样的持续时间:

(1, 2, 3, 11)

它采用天/小时/分钟/秒格式。我怎样才能显示类似:1 days, 2 hours and 3 minutes. 我不需要秒。所以,如果持续时间是:

(0, 2, 3, 1)

它应该显示为2 hours and 3 minutes. 如果持续时间是:

(0, 0, 3, 11)

它应该显示为3 minutes.

我怎样才能做到这一点?谢谢

4

2 回答 2

3

这是 Python 2.6 和英语单数/复数的编辑答案:

def f(x):
    parts = ['%d %s%s' % (a, p, ('', 's')[a > 1]) for a,p in zip(x, ('day', 'hour', 'minute')) if a]
    return ' and '.join(c for c in [', '.join(parts[:-1]), parts[-1]] if c)

测试:

>>> print f((1, 2, 3, 11))
1 day, 2 hours and 3 minutes

>>> print f((0, 2, 3, 1))
2 hours and 3 minutes

>>> print f((0, 0, 3, 11))
3 minutes
于 2013-01-11T12:51:05.887 回答
1

你打算做多少?

如果它很多,并且会重复很多,你可以写一个函数来为你做;

def days(t):
    oxford_comma = False
    a = [" day", " hour", " minute"]
    s = []
    if len(t) != 4:
        return "incorrect format"
    else:
        for i in range(3):
            if t[i] != 0:
                plural = "s" if t[i] > 1 else ""
                s.append(str(t[i]) + a[i] + plural + ", ")


        if len(s) > 1:
            if not oxford_comma:
                s[-2] = s[-2].replace(",","")
            s.insert(len(s)-1,"and ")
        return "".join(s)[:-2]


    print days((1,2,3,11))      #1 day, 2 hours, and 3 minutes
    print days((0,2,3,1))       #2 hours, and 3 minutes
    print days((0,0,3,11))      #3 minutes
    print days((1,1,1,11))      #1 day, 1 hour, and 1 minute

oxford_comma如果你想改变它。

它还考虑了复数。

抱歉,它有点乱——它肯定可以清理干净——很匆忙!

于 2013-01-11T12:48:56.640 回答