Str in Python's map and sum
Why do you need to use the function 'str' in the following code?
I am trying to count the sum of digits in 开发者_高级运维a number.
My code
for i in number:
sum(map(int, str(i))
where number is the following array
[7,79,9]
I read my code as follows
- loop though the array such that
- count sum of the integer digits
- by getting given digits in a number by map increasingly
- such that each object (given number) is converted to String // This does not make sense
Manual says this for str
Type: type
Base Class: <type 'type'>
String Form: <type 'str'>
Namespace: Python builtin
Docstring:
str(object) -> string
Return a nice string representation of the object.
If the argument is a string, the return value is the same object.
Given 79
you need to get [7, 9]
in order to sum up this list.
What does it mean to split a number into digits? It means to represent the number in a numerical system with some base (base 10
in this case). E. g. 79
is 7 * 10**1 + 9 * 10**0
.
And what is the simplest (well, at least in this context) way to get such a representation of a number? To convert it to a string of decimals!
Your code does exactly that:
>>> str(79)
'79'
# Another way to say this is [int(c) for c in str(79)]
>>> map(int, str(79))
[7, 9]
>>> sum(map(int, str(79)))
16
What happens when you try that code without using str()
?
The str()
is used to convert the integer into a sequence of characters, so that map()
can iterate over the sequence. The key point here is that a "string" can be treated as a "sequence of characters".
Why do you need to use the function 'str' in the following code?
Because map takes an iterable, like a list or a tuple or a string.
The code in question adds upp all the numbers in an integer. And it does it by a little clever hack. It converts the number into a sequence of numbers by doing
map(int, str(i))
This will convert the integer 2009 to the list [2, 0, 0, 9]. The sum() then adds all this integers up, and you get 11.
A less hacky version would be:
>>> number = [7,79,9]
>>> for i in number:
... result = 0
... while i:
... i, n = divmod(i, 10)
... result +=n
... print result
...
7
16
9
But your version is admittedly more clever.
精彩评论