简体   繁体   中英

Can't figure out why code working in Python 3 , but not 2.7

I wrote and tested the code below with Python 3 and it works fine:

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

In Python3 the above returns:

1 minute and 2 seconds

However, the same code in Python 2.7 returns:

62 seconds

I can't for the life of me figure out why. Any help would be greatly appreciated.

The answers are different because the items in your dict are used in a different order in the two versions.

In Python 2, dicts are unordered, so you need to do more to get the items in the order you want.

BTW, don't use "dict" or "list" as variable names, it makes debugging harder.

Here's fixed code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM