[英]How do I assign a numerical value to each uppercase Letter?
How do i assign a numerical value to each uppercase letter, and then use it later via string and then add up the values. 如何为每个大写字母分配一个数值,然后通过字符串使用它,然后将值相加。
EG. 例如。
A = 1, B = 2, C = 3 (etc..)
string = 'ABC'
Then return the answer 6 (in this case). 然后返回答案6(在这种情况下)。
base = ord('A') - 1
mystring = 'ABC'
print sum(ord(char) - base for char in mystring)
import string
letter_to_numeral = dict(zip(string.uppercase, range(1, len(string.uppercase) + 1) ))
print letter_to_numeral
>>> {'A': 1, 'C': 3, 'B': 2, 'E': 5, 'D': 4, 'G': 7, 'F': 6, 'I': 9, 'H': 8, 'K': 11, 'J': 10, 'M': 13, 'L': 12, 'O': 15, 'N': 14, 'Q': 17, 'P': 16, 'S': 19, 'R': 18, 'U': 21, 'T': 20, 'W': 23, 'V': 22, 'Y': 25, 'X': 24, 'Z': 26}
def score_string(s):
return sum([letter_to_numeral[character] for character in s])
score_string('ABC')
>>> 6
Enumerate can do the numbering for you: 枚举可以为您编号:
import string
numerology_table = dict((ch,num+1)
for (num,ch) in enumerate(string.ascii_letters[:26].upper()))
or even better, you can have enumerate start at 1 instead of the default of 0: 甚至更好,您可以枚举从1开始而不是默认值0:
numerology_table = dict((ch,num)
for (num,ch) in enumerate(string.ascii_letters[:26].upper(),
start=1))
def getvalue(mystring):
letterdict = dict(zip('ABCDEFGHIJKLMNOPQRSTUVWXYZ',range(1,27)))
return sum(letterdict[c] for c in mystring)
If you are using Python3: 如果您使用的是Python3:
result = 0
mystring = 'ABC'
for char in mystring.encode('ascii'):
result += char - 64
>>> result
6
Golfy answer certain to annoy your professor: 高尔夫回答肯定会惹恼你的教授:
>>> s = 'ABC'
>>> sum(map(ord,s),-64*len(s))
6
The most sensible answer is of course using ord
as shown earlier. 最明智的答案当然是使用ord
,如前所示。 But for those who chose to construct a dictionary, I would rather just use the index in the string: 但对于那些选择构建字典的人,我宁愿只使用字符串中的索引:
>>> import string
>>> mystring = 'ABC'
>>> sum(string.uppercase.index(c) + 1 for c in mystring)
6
定义变量后,您只需返回答案或打印答案A = 1 B = 2 C = 3总计= A + B + C打印(总计)返回总计
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.