我正在做一个编码挑战,这个挑战是返回原始参数+序数。示例:
return_end_of_number(553(➞"553-RD">
return_end_of_number(34(➞"第34位">
return_end_of_number(1231(➞"1231-ST">
return_end_of_number(22(➞"22岁">
以下是顶级解决方案:
def return_end_of_number(num):
d = {1: 'ST', 2: 'ND', 3: 'RD'}
return '{}-{}'.format(num, d.get(num%10, 'TH'))
虽然我解决这个问题的想法是正确的,但我从来没有想过这样写。这个部分的要素是什么:
d.get(num%10, 'TH')
我看到他/她正在使用num mod 10来获取最后一个数字,但"TH"是d.get设置默认值的参数吗?
dict.get(...)
方法采用可选的默认参数:https://docs.python.org/3/library/stdtypes.html#dict.get
get(key[,default](
如果键在字典中,则返回密钥的值,否则默认值。如果未给定默认,则默认为
None
,因此此方法永远不会引发KeyError
。
因此,如果我们在python repl:中跟踪您的示例
>>> d = {1: 'ST', 2: 'ND', 3: 'RD'}
# Notice I'm not including the default argument
>>> d.get(3)
'RD'
# The key `4` doesn't exist.
>>> d.get(4) is None
True
# If we use a default for when the key doesn't exist
>>> d.get(4, 'this is the default value')
'this is the default value'
>>> d.get(4, 'TH')
'TH'
解释器外壳可用于回答以下问题:
help(dict.get)
>>> get(self, key, default=None, /)
>>> Return the value for key if key is in the dictionary, else default.
num%10
只传递任意整数的位置号。
dictionary.get(keyname, value)
这里,第二个参数值是可选的。当您传递第二个参数值时,如果在字典中找不到键,它将返回作为参数传递的"value"。
对于您的解决方案,当使用.get((方法搜索(num%10(给定的1,2,3以外的键时,将返回第二个参数"value"。
参考:https://www.w3schools.com/python/ref_dictionary_get.asp
你说得对,这是默认值!
如果找不到密钥,dict[key]抛出KeyError
:
>>> numbers = {'one':1, 'two':2, 'three':3}
>>> numbers['four']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'four'
dict.get(key(更好,当找不到密钥时返回默认的None
:
>>> numbers.get('four')
>>>
然而,如果我想要一个自定义默认值,我会说dict.get(key,custom_defect(:
>>> numbers.get('four', 'not found')
'not found'