根据字典值增加值

2024-06-16 12:50:23 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一本这样的字典

SCRABBLE_LETTER_VALUES = { 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10 }

现在,假设我有一个这样的变量。你知道吗

letter = 'i'

我想把相应的值加到可变分数上。既然字母等于i,那么分数应该等于1


Tags: 字典字母分数valuesletterscrabble
3条回答

使用dictionary_name[key]访问字典值。所以在这种情况下:

score+=SCRABBLE_LETTER_VALUES[letter]

在执行此操作之前,还需要将score分配给某个对象:

score=0

您可能会发现阅读有关词典的文档很有用:https://docs.python.org/3/tutorial/datastructures.html#dictionaries

首先你需要知道how python plays with dictionary-你问的问题非常简单,因此人们投了反对票!你知道吗

回答您的问题:

您已经记住了下面的代码,并且正在为剩下的代码而奋斗。我将根据你的陈述相应地回答他们。你知道吗

SCRABBLE_LETTER_VALUES = {
    'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10
}
letter = 'i'

在python中,为了获得对应键的值,它的工作方式类似于dictionary[key],它给出了输出。你知道吗

所以对于你的问题,如果我们做SCRABBLE_LETTER_VALUES[letter],它和做SCRABBLE_LETTER_VALUES['i']一样,其中'i'是关键,我们会得到1作为输出。你知道吗

因此对于SCRABBLE_LETTER_VALUES[letter]我们得到1作为输出!你知道吗

I want to add the corresponding value to the variable score. So since letter is equal to i

将相应的值赋给变量得分是score = SCRABBLE_LETTER_VALUES[letter]

then score should equal 1

我们现在肯定地知道score的值是1。不是吗?你知道吗

因为SCRABBLE_LETTER_VALUES[letter]值是1,而letter= 'i'因此score1

SCRABBLE_LETTER_VALUES = {'a': 1, 'c': 3, 'b': 3, 'e': 1, 'd': 2, 'g': 2, 'f': 4, 'i': 1, 'h': 4, 'k': 5, 'j': 8, 'm': 3, 'l': 1, 'o': 1, 'n': 1, 'q': 10, 'p': 3, 's': 1, 'r': 1, 'u': 1, 't': 1, 'w': 4, 'v': 4, 'y': 4, 'x': 8, 'z': 10}

>>> SCRABBLE_LETTER_VALUES['i']
1
>>> SCRABBLE_LETTER_VALUES['z']
10

相关问题 更多 >