繁体   English   中英

有人可以在 Python 中解释这个 dict().get 函数吗?

[英]Can someone explain this dict().get function in Python?

我正在做一个编码挑战,这个特殊的挑战是返回原始参数 + 序数。 例子:

return_end_of_number(553) ➞ "553-RD"

return_end_of_number(34) ➞ "34-TH"

return_end_of_number(1231) ➞ "1231-ST"

return_end_of_number(22) ➞ "22-ND"

这是顶级解决方案:

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 的参数来设置默认值还是什么?

解释器外壳对于回答这样的问题很有用:

help(dict.get)

>>> get(self, key, default=None, /) 
>>> Return the value for key if key is in the dictionary, else default.

num%10只提供任何整数的位置编号。

dict.get(...)方法采用可选的默认参数: https : //docs.python.org/3/library/stdtypes.html#dict.get

获取(键 [,默认])

如果key在字典中,则返回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'

get() 方法返回具有指定键的项目的值。 句法

dictionary.get(keyname, value)

这里,第二个参数值是可选的。 当您传递第二个参数值时,如果在字典中找不到该键,它将返回作为参数传递的“值”。

对于您的解决方案,当使用 .get() 方法搜索 (num%10) 给出的 1,2,3 以外的键时,将返回第二个参数“值”。

参考: 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_default):

>>> numbers.get('four', 'not found')
'not found'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM