Python 3如何找到名为字符串的变量?

时间:2018-12-08 14:25:14

标签: python python-3.x

对不起,我不知道如何正确命名此问题:/ 我有每个字母的变量。当我检查每个字母的单词时,我想将+1添加到当前与字母im相同的变量中。 我希望它像这样工作: locals(letter) += 1

2 个答案:

答案 0 :(得分:4)

为所有英文字母创建变量并使用它们(26个变量!听起来巨大)是不明智的。

最好采用Counter方法:

from collections import Counter

word = 'hello'
print(Counter(word))
# Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})

如果需要所有字母计数:

import string
from collections import Counter

all_letters = string.ascii_lowercase
word = 'hello'
d = dict.fromkeys(all_letters, 0)
d.update(Counter(word))
print(d)

答案 1 :(得分:1)

您可以执行以下操作来访问变量...

locals()[letter]

但是您需要检查以字符串命名的变量的值这一事实表明设计选择错误。

相反,您应该将这些值存储在dict中。

letters = {
    'a': 0,
    'b': 0,
    'c': 0,
    ...
}

letters['a'] += 1