理解 Python 中的 .get() 方法 [英] Understanding .get() method in Python

查看:60
本文介绍了理解 Python 中的 .get() 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

sentence = "The quick brown fox jumped over the lazy dog."
characters = {}

for character in sentence:
    characters[character] = characters.get(character, 0) + 1 

print(characters)

我不明白 characters.get(character, 0) + 1 在做什么,其余的看起来很简单.

I don't understand what characters.get(character, 0) + 1 is doing, rest all seems pretty straightforward.

推荐答案

dict 的 get 方法(例如 characters)的工作方式就像索引 dict,除此之外,如果键丢失,而不是引发 KeyError 它返回默认值(如果你调用 .get 只带一个参数,键,默认值是 None).

The get method of a dict (like for example characters) works just like indexing the dict, except that, if the key is missing, instead of raising a KeyError it returns the default value (if you call .get with just one argument, the key, the default value is None).

所以一个等效的 Python 函数(其中调用 myget(d, k, v) 就像 d.get(k, v) 可能是:

So an equivalent Python function (where calling myget(d, k, v) is just like d.get(k, v) might be:

def myget(d, k, v=None):
  try: return d[k]
  except KeyError: return v

您问题中的示例代码显然是在尝试计算每个字符的出现次数:如果它已经对给定字符进行了计数,则 get 将返回它(因此它只是增加了 1),否则 get 返回 0(因此在字符串中第一次出现字符时,递增正确给出 1).

The sample code in your question is clearly trying to count the number of occurrences of each character: if it already has a count for a given character, get returns it (so it's just incremented by one), else get returns 0 (so the incrementing correctly gives 1 at a character's first occurrence in the string).

这篇关于理解 Python 中的 .get() 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆