Skip to main content
 首页 » 编程设计

python之Python 的 map 和 sum 中的 str

2025年05月04日24insus

为什么需要在下面的代码中使用“str”函数?

我正在尝试计算数字中的数字总和。

我的代码

for i in number: 
    sum(map(int, str(i)) 

其中number是后面的数组

[7,79,9] 

我阅读我的代码如下

  1. 遍历数组使得
  2. 计算整数位数的总和
  3. 越来越多地通过映射获取数字中的给定数字
  4. 这样每个对象(给定的数字)都转换为字符串//这没有意义

手册为 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. 

请您参考如下方法:

给定 79,您需要得到 [7, 9] 才能对这个列表求和。

将数字拆分成数字是什么意思?它意味着用一些基数表示数字系统中的数字(在本例中为基数 10)。例如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