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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16297430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:14:24  来源:igfitidea点击:

Using a for loop to add values in a list

pythonpython-3.x

提问by Aaron

I am new to Python and am having trouble wrapping my head around why this doesn't work.

我是 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)

Basically, I want a user to enter 123 for example and then get the sum of 1 and 2 and 3.

基本上,我希望用户输入 123,然后得到 1 和 2 和 3 的总和。

I am getting this error and do not know how to combat it.

我收到这个错误,不知道如何解决它。

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'

I just can't find the answer to this in my textbook and don't understand why my second for loop won't iterate the list and accumulate the value to total.

我只是在我的教科书中找不到答案,也不明白为什么我的第二个 for 循环不会迭代列表并将值累积到总数。

回答by Gareth Webber

You need to convert the strings to integers before you can add them.

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

Try changing this line:

尝试更改此行:

number_list.append(num)

To this:

对此:

number_list.append(int(num))

Alternatively, a more Pythonic way of doing this would be to use the sum()function, and map()to convert each string in your initial list to an integer:

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

number_string = input("Enter some numbers: ")

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

Be aware though, that if you input something like "123abc" your program will crash. If you are interested, look at handling exceptions, specifically a ValueError.

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

回答by Sameer H. Ibra

Change the line to:

将该行更改为:

total += int(value)

or

或者

total = total + int(value)

P.S. Both of the code lines are equivalent.

PS 两行代码都是等价的。

回答by Nipun Batra

Here is the official documentation about inputin Python 3

这是关于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"

So when you do an inputin the first line of your example you are basically getting strings.

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

Now you need to convert these stringto intbefore summing up. So you would basically do:

现在您需要在总结之前将这些字符串转换为int。所以你基本上会这样做:

total = total + int(value)

About Debugging:

关于调试:

When in similar situation, when you get errors like: unsupported operand type(s) for +=: 'int' and 'str', you can make use of the type()function.

在类似情况下,当您收到类似以下错误时: += 的不支持的操作数类型:'int' 和 'str',您可以使用type()函数。

Doing type(num) would tell you that it is a string. Obviously stringand intcannot be added.

做 type(num) 会告诉你它是一个字符串。显然stringint不能相加。

`

`

回答by Bhavish Agarwal

I guess people have correctly pointed out the flaw in your code i.e the type conversion from string to int. However following is a more pythonic way of writing the same logic:

我猜人们已经正确地指出了您代码中的缺陷,即从字符串到 int 的类型转换。但是,以下是编写相同逻辑的更pythonic 的方式:

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

Here, we are using a generator, list comprehension and the library function sum.

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

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

EDIT:

编辑:

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