我需要字符串字母值 ex 中的总和。 一 = 1 b = 2 c = 3 d = 4
alphabet = 'abcdefghijklmnopqrstuvwxyz'
v1
string = "abcd"
# #result = sum(string) so
if string[0] and string[1] and string[2] and string[3] in alphabet:
if string[0] is alphabet[0] and string[1] is alphabet[1] and string[2] is alphabet[2] and string[3] is alphabet[3]:
print(a+b+c+d)
v2
string = ("ab","aa","dc",)
if string[0][0] and string[0][1] and string[1][0] and string[1][1] and string[2][0] and string[2][1] in alphabet:
if string[0] is alphabet[0] and string[1] is alphabet[1] and string[2] is alphabet[2] and string[3] is alphabet[3]:
print(a+b+c+d)
解决方法是什么?你能帮帮我吗
最佳答案
使用 sum()
function和一个 generator expression ;从 string.ascii_lowercase
构建的字典可以作为获取每个字母整数值的方法:
from string import ascii_lowercase
letter_value = {c: i for i, c in enumerate(ascii_lowercase, 1)}
wordsum = sum(letter_value.get(c, 0) for c in word if c)
enumerate(ascii_lowercase, 1)
在迭代时产生 (index, letter)
对,从 1 开始。这给你 (1, 'a ')
, (2, 'b')
等,可以转换为字典中的c:i
字母对,将字母映射为整数.
接下来,使用 dict.get()
method让你选择一个默认值;对于输入字符串中的任何字符,您可以查找数值并将其映射为整数,但如果该字符不是小写字母,则返回 0
。循环中的 sum(...)
部分然后简单地将这些值相加。
如果您需要支持单词序列,只需再次使用sum()
。将上面的 sum()
调用放在一个函数中,并将该函数应用于序列中的每个单词:
from string import ascii_lowercase
letter_value = {c: i for i, c in enumerate(ascii_lowercase, 1)}
def sum_word(word):
return sum(letter_value.get(c, 0) for c in word if c)
def sum_words(words):
return sum(sum_word(word) for word in words)
关于string - python3 sum in stings 每个字母值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33996422/