我使用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
我无法为自己的生活弄清楚原因。任何帮助将不胜感激。
答案 0 :(得分:8)
答案是不同的,因为在两个版本中,字典中的项目使用的顺序不同。
在Python 2中,字典是无序的,因此您需要做更多的事情才能按想要的顺序获取项目。
顺便说一句,不要使用“ dict”或“ list”作为变量名,这会使调试更加困难。
这里是固定代码:
error:::{"headers":{"normalizedNames":{},"lazyUpdate":null},"status":401,"statusText":"Unauthorized","url":"https://graph.microsoft.com/beta/sites/4development106.sharepoint.com:/sites/DBSchenker:/lists/OEC_Docs/items","ok":false,"name":"HttpErrorResponse","message":"Http failure response for https://graph.microsoft.com/beta/sites/4development106.sharepoint.com:/sites/DBSchenker:/lists/OEC_Docs/items: 401 Unauthorized","error":{"error":{"code":"InvalidAuthenticationToken","message":"Access token validation failure.","innerError":{"request-id":"f5a77afc-0d92-49a0-92c4-e727e056d0a9","date":"2018-10-30T01:42:02"}}}}