![](/img/trans.png)
[英]Hangman with dashes in Python - can't figure out why the code is not working
[英]Can't figure out why code working in Python 3 , but not 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
我不能為我的生活找出原因。 任何幫助將不勝感激。
答案是不同的,因為你的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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.