使用 for 循环在列表中添加值

3

我是Python的新手,目前遇到了一个问题,不明白为什么这样做不起作用。

number_string = input("Enter some numbers: ")

# Create List
number_list = [0]

# Create variable to use as accumulator
total = 0

# Use for loop to take single int from string and put in list
for num in number_string:
    number_list.append(num)

# Sum the list
for value in number_list:
    total += value

print(total)

基本上,我希望用户输入例如 123,然后得到 1、2 和 3 的总和。
我遇到了这个错误,不知道该如何解决。
Traceback (most recent call last):
  File "/Users/nathanlakes/Desktop/Q12.py", line 15, in <module>
    total += value
TypeError: unsupported operand type(s) for +=: 'int' and 'str'

我在教科书里找不到答案,也不明白为什么我的第二个for循环不能遍历列表并将值累加到总和中。

4个回答

11

在您执行加法运算前,需要将字符串转换为整数。

尝试更改此行:

number_list.append(num)

变成这样:

number_list.append(int(num))

另一种更符合Python风格的方法是使用sum()函数和map()函数将初始列表中的每个字符串转换为整数:

number_string = input("Enter some numbers: ")

print(sum(map(int, number_string)))

需要注意的是,如果你输入类似于“123abc”这样的内容,你的程序将会崩溃。如果你有兴趣,可以查看如何处理异常,特别是ValueError


2
我认同这是一个可行的解决方案,但基于命名的考虑,把它添加到名为“number_list”的列表时将其转换为整数会更合理。否则,他每次使用这些数字都需要进行类型转换。 - eandersson
同意,我已经编辑了我的帖子。 - Pep_8_Guardiola
你是在建议当我添加到列表时,添加 int() 吗? - Aaron
1
@Nate 是的,这样你就把字符串转换成了整数,可以加到“total”中。 - Pep_8_Guardiola

0

这里是关于 Python 3 中输入的官方文档。

 input([prompt])

If the prompt argument is present, it is written to standard output without a trailing    newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. Example:

>>> s = input('--> ')
--> Monty Python's Flying Circus
>>> s
"Monty Python's Flying Circus"

因此,当您在示例的第一行进行输入时,基本上是获取字符串。

现在,您需要在求和之前将这些字符串转换为整数。因此,您基本上会执行以下操作:

total = total + int(value)

关于调试:

当你遇到类似的错误,比如:unsupported operand type(s) for +=: 'int' and 'str',你可以使用 type() 函数。

执行 type(num) 会告诉你它是一个字符串。显然,字符串整数 不能相加。

`


0

我猜人们已经正确指出了你代码中的缺陷,即从字符串转换为整数的类型转换。然而,以下是一种更具Python风格的编写相同逻辑的方式:

number_string = input("Enter some numbers: ")
print  sum(int(n) for n in number_string)

在这里,我们使用了生成器、列表推导式和库函数 sum。

>>> number_string = "123"
>>> sum(int(n) for n in number_string)
6
>>> 

编辑:

number_string = input("Enter some numbers: ")
print  sum(map(int, number_string))

2
或者 sum(map(int, number_string)) - johnsyweb

0

把这一行改为:

total += int(value)

或者

total = total + int(value)

附言:这两行代码是等价的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接