简体   繁体   中英

Error while using ord() in reduce function in Python

I have the following reduce function in python which is supposed to return the sum of the ASCII values of all the characters in the string. For example for the string "BOY" the reduce function should return 234.

reduce(lambda x,y:ord(x)+ord(y),list("BOY"))

But im getting the following error:

TypeError: ord() expected string of length 1, but int found

What is the problem with my code?

reduce(lambda x,y:ord(x)+ord(y),list("BOY"))

Think about how this reduces:

'B' 'O' 'Y'
145 'Y'

What is ord(145) + ord('Y') ? Its an error.

Others have suggested:

reduce(lambda x, y: x + ord(y), "BOY", 0)

Which reduces like:

0 'B' 'O' 'Y'
66 'O' 'Y'
145 'Y'
234

I'd recommend

sum(map(ord, "BOY"))

This should be

>>> reduce(lambda x, y: x + ord(y), "BOY", 0)
234

The left operand x of the lambda function will always be the result of the previous invocation of the function, so it's an integer. Wee need to provide a start value 0 , but it's not necessary to convert the string to a list -- the string is iterable itself.

You would have avoided this problem if you would have followed Guido's recommendation to write the accumulation loop explicitly :

result = 0:
for x in "BOY":
    result += ord(x)

为什么不sum(map(ord, "BOY"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM