Can';我不明白为什么代码使用Python 3,而不是2.7
我用Python 3编写并测试了下面的代码,效果很好:Can';我不明白为什么代码使用Python 3,而不是2.7,python,python-3.x,python-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: cou
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中的项目使用顺序不同 在Python2中,dict是无序的,因此您需要做更多的工作来按照您想要的顺序获取项目 顺便说一句,不要使用“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))
完美的解决方案。这是很有价值的,知道听写在2和3中的行为不同。非常感谢!