2

I have my own name saved as a string under the variable name. I want to find the character code for each character in my name and then add them all up using a for loop. This is what I've started with, no idea if it's staring about the right way

name = "Ashley Marie"
for index in name:
    ans = ord(index)
4

2 回答 2

4

您可以使用mapord函数应用于所有字符,然后使用sum函数计算总和:

>>> name = "Ashley Marie"
>>> 
>>> sum(map(ord,name))
1140

您也可以使用列表推导来应用ord您的角色,但是当您处理内置函数时map,性能会稍微好一些!所以我建议map

同样对于最长的字符串,您可以在中使用生成器表达式sum,它不会创建列表并且可以节省大量内存:

sum(ord(i) for i in name)
于 2015-06-25T08:40:52.017 回答
1

Kasra 解决方案是正确的,但您要求使用“for 循环”......所以它是:

 name = "Ashley Marie"
    sum = 0
    for ch in map(ord, name):
        sum += ch
    print sum

或者

name = "Ashley Marie"
sum = 0
 for c in name:
    sum += ord(c)
print sum
于 2015-06-25T08:52:16.670 回答