【问题标题】:Can't figure out why code working in Python 3 , but not 2.7无法弄清楚为什么代码在 Python 3 中工作,但不是 2.7
【发布时间】:2018-10-30 10:06:34
【问题描述】:

我用 Python 3 编写并测试了下面的代码,它运行良好:

def format_duration(seconds):
    dict = {'year': 86400*365, 'day': 86400, 'hour': 3600, 'minute': 60, 'second': 1}
    secs = seconds
    count = []
    for k, v in dict.items():
        if secs // v != 0:
            count.append((secs // v, k))
            secs %= v

    list = [str(n) + ' ' + (unit if n == 1 else unit + 's') for n, unit in count]

    if len(list) > 1:
        result = ', '.join(list[:-1]) + ' and ' + list[-1]
    else:
        result = list[0]

    return result


print(format_duration(62))

在 Python3 中,以上返回:

1 minute and 2 seconds

但是,Python 2.7 中的相同代码返回:

62 seconds

我一辈子都想不通为什么。任何帮助将不胜感激。

【问题讨论】:

    标签: python python-3.x python-2.7


    【解决方案1】:

    答案不同,因为您的 dict 中的项目在两个版本中的使用顺序不同。

    在 Python 2 中,dicts 是无序的,所以你需要做更多的事情来按你想要的顺序获取项目。

    顺便说一句,不要使用“dict”或“list”作为变量名,这会使调试更加困难。

    这里是固定代码:

    def format_duration(seconds):
        units = [('year', 86400*365), ('day', 86400), ('hour', 3600), ('minute', 60), ('second', 1)]
        secs = seconds
        count = []
        for uname, usecs in units:
            if secs // usecs != 0:
                count.append((secs // usecs, uname))
                secs %= usecs
    
        words = [str(n) + ' ' + (unit if n == 1 else unit + 's') for n, unit in count]
    
        if len(words) > 1:
            result = ', '.join(words[:-1]) + ' and ' + words[-1]
        else:
            result = words[0]
    
        return result
    
    
    print(format_duration(62))
    

    【讨论】:

    • 完美解决方案。知道 dicts 在 2 和 3 中的行为不同是很有价值的。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 1970-01-01
    • 2021-05-29
    相关资源
    最近更新 更多