python - 无法弄清楚为什么代码在 Python 3 中工作,而不是 2.7

标签 python python-3.x python-2.7

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

关于python - 无法弄清楚为什么代码在 Python 3 中工作,而不是 2.7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53056229/

相关文章:

python - 如何模拟类实例属性?

python - 为什么内置的 python 帮助功能不显示所有可能的命令?

python - 正则表达式 findall 匹配字符串中的字母 "a"到 "z"后跟另一个字符

python - 如何获取 pandas 数据框对象值的模式?

python - 从椭球置信区域均匀采样

python - matplotlib继承自datetime类plot

python - 将 .ui 文件转换为 .py 文件时出错

python-2.7 - ZMQ IOLoop 实例写入/读取工作流

Python 类方法在调用另一个方法时运行

python - 当应用堆叠集成时,H2O 如何衡量基础学习器的权重?