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

标签 python python-3.x

<分区>

我是 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 循环不会迭代列表并将值累加到总计。

最佳答案

您需要先将字符串转换为整数,然后才能添加它们。

尝试改变这一行:

number_list.append(num)

对此:

number_list.append(int(num))

或者,一种更 Pythonic 的方法是使用 sum() 函数和 map() 将初始列表中的每个字符串转换为整数:

number_string = input("Enter some numbers: ")

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

但请注意,如果您输入类似“123abc”的内容,您的程序将会崩溃。有兴趣看处理exceptions ,特别是 ValueError .

关于python - 使用 for 循环在列表中添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16297430/

相关文章:

python - CMD Prompt 和 Sublime Buid 中的不同 OP

python - 如何在 lxml 中使用 cssselect 选择具有确切类的元素?

使用 numpy/scipy 进行 Python 多处理速度较慢

python - 如何在不使用希尔伯特索引的情况下沿希尔伯特曲线对点进行排序?

python - 使用 wxPython 在 Python 中的文本上鼠标事件

python - 多次发送时sendto出现问题(Python)

python - 按索引遍历数据框

python - 使用索引列表从字典中获取值

Python如何获取多行字符串的最后N行

python - 如何强制 Python (EMCEE) 在先前定义的范围之间精确移动