为什么需要在以下代码中使用'str'函数?
我试图计算一个数字中的数字总和.
我的代码
for i in number:
sum(map(int, str(i))
Run Code Online (Sandbox Code Playgroud)
其中number是以下数组
[7,79,9]
Run Code Online (Sandbox Code Playgroud)
我按如下方式阅读了我的代码
手册对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.
Run Code Online (Sandbox Code Playgroud)
鉴于79你需要得到[7, 9]总结这个列表.
将数字拆分成数字意味着什么?它意味着在具有一定基数的数值系统中表示数字(10在这种情况下为基数).E. g.79是7 * 10**1 + 9 * 10**0.
什么是最简单的(好吧,至少在这种情况下)获得这样一个数字表示的方式?将其转换为小数字串!
你的代码完全是这样的:
>>> 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
Run Code Online (Sandbox Code Playgroud)