gpt4 book ai didi

python - 使用 Get 访问字典

转载 作者:太空宇宙 更新时间:2023-11-03 18:12:42 25 4
gpt4 key购买 nike

For this problem assume the following assignment statement has been executed.

weekdays = {'Sunday':0, 'Monday':1, 'Tuesday':2, 'Wednesday':3,
'Thursday':4, 'Friday':5, 'Saturday':6}

Assume the variable day contains a value that may or may not be the name of a day. Write an assignment statement using get that assigns to day_num the day number if day contains the name of a day and -1 otherwise.

For example, if day is 'Wednesday' then day_num should be 3 and if day is 'Talk Like a Pirate Day' then day_num should be -1.

这是我的代码:

day_num = weekdays.get(day)
if day_num==None:
day_num=-1

我就是不明白为什么还是错误;我认为这是正确的。作业系统不断显示

You should use only one assignment statement (and nothing else)

最佳答案

您正在使用两个赋值语句。也许你应该给dict.get() 第二个参数:

day_num = weekdays.get(day, -1)

如果字典中不存在day,则默认返回第二个参数;默认值是 None,但这里我返回 -1

这可以为您节省一次 is None 测试和第二次作业。

关于python - 使用 Get 访问字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25588446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com