string - python3 sum in stings 每个字母值

标签 string algorithm sorting python-3.x

我需要字符串字母值 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/

相关文章:

c# - 检查最佳路径

javascript - 来回循环的for循环

c# - .Sort(Function(x, y) -> 当没有要排序的内容时重新排列列表(即所有排序字段具有相同的值)

Python:西里尔字母处理

javascript - Mustache 模板将表达式与某个字符串串联

java - 了解运算符优先级

PHP 货币格式

python - Minimax 解释 "for dummies"

r - 使用 ggplot2 根据其大小(即数值)对条形图进行排序

c - 排序结构记录