“如何像计算机一样思考”这本书的第4.17节有练习 科学家:学习使用Python 3“第3版
“编写一个函数day_name,将整数0到6转换为一天的名称。假定day 0是“ Sunday”。再次声明None,如果该函数的参数无效。”
我写了下面的代码,大部分解决了这个问题,除了我不明白如何为无效的参数返回“ None”。请协助...
def day_name(x):
days=["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
return days[x]
print(day_name(5))
如果我print(day_name(7))
,它将返回python错误而不是“ None”
答案 0 :(得分:2)
向您的函数添加验证。您可以明确地做到这一点:
if x in range(7):
return days[x]
else:
return None
这被称为跳下前:您先检查days[x]
是否存在,然后再尝试选择它。
或者您可以让选择失败并捕获错误:
try:
return days[x]
except IndexError:
return None
答案 1 :(得分:1)
您正在使用列表数据结构。它基于索引。
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
0 1 2 3 4 5 6
当我们访问print(day_name(7))
时,我们试图访问索引7
,该索引不可用。因此,它引发了错误。
更好的方法是
def day_name(x):
days = {
0: 'Sunday',
1: 'Monday',
2: 'Tuesday',
3: 'Wednesday',
4: 'Thursday',
5: 'Friday',
6: 'Saturday'
}
return dic.get(x)
print(day_name(7))
字典使用散列技术的速度更快。
from time import time
t = time()
lst = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
try:
print(lst[7])
except IndexError:
pass
print(time() - t)
t = time()
days = {
0: 'Sunday',
1: 'Monday',
2: 'Tuesday',
3: 'Wednesday',
4: 'Thursday',
5: 'Friday',
6: 'Saturday'
}
print(days.get(7))
print(time() - t)
None
3.09944152832e-05
None
1.09672546387e-05
有关更多出轨结帐https://learnbatta.com/course/python/python-working-with-lists/
答案 2 :(得分:0)
def day_name(x):
days=["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
try:
return days[x]
except:
return None
您可以使用for循环,但这是更好的方法。 https://docs.python.org/3/tutorial/errors.html#handling-exceptions。
正如@Derte所说的,只捕获特定的异常而不是一揽子除外语句(如以下语句)也是一种好习惯:
def day_name(x):
days=["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
try:
return days[x]
except IndexError as e:
print(e)
return None
这是使用timeit库的时间测试:
import timeit
def day_name_eafp(x):
days=["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
try:
return days[x]
except IndexError as e:
return None
def day_name_dict(x):
days = {
0: 'Sunday',
1: 'Monday',
2: 'Tuesday',
3: 'Wednesday',
4: 'Thursday',
5: 'Friday',
6: 'Saturday'
}
return days.get(x)
def wrapper(func, *args, **kwargs):
def wrapped():
return func(*args, **kwargs)
return wrapped
x=7
wrapped_eafp = wrapper(day_name_eafp, x)
wrapped_dict = wrapper(day_name_dict, x)
timeit.timeit(wrapped_eafp, number=100000)
>>0.05935070099803852
timeit.timeit(wrapped_dict, number=100000)
>>0.06682577800165745
这意味着速度是可比的。所以,当然,您应该使用更Python化的方式。
答案 3 :(得分:0)
函数/方法'day_name'持有一个dict,该索引从日期索引指向日期名称。pythondict附带一个名为'get'的函数,您可以在此处阅读:https://www.tutorialspoint.com/python/dictionary_get.htm。 “ get”功能可以处理day_index和日期名称之间不匹配的情况。
def day_name(day_index):
days = {0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday"}
return days.get(day_index, None)
print(day_name(4)) # Thursday
print(day_name(44)) # None