python列表for循环 加入新列表_关于python:使用for循环在列表中添加值

 2023-09-15 阅读 25 评论 0

摘要:本问题已经有最佳答案,请猛点这里访问。我是Python的新手,我无法解决为什么这不起作用。number_string = input("Enter some numbers:")# Create Listpython循环语法?number_list = [0]# Create variable to use as accumulatortotal = 0#

本问题已经有最佳答案,请猛点这里访问。

我是Python的新手,我无法解决为什么这不起作用。

number_string = input("Enter some numbers:")

# Create List

python循环语法?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:

c语言for循环、number_list.append(num)

# Sum the list

for value in number_list:

total += value

print(total)

python for in?基本上,我希望用户输入123例如然后得到1和2和3之和。

我收到此错误,不知道如何打击它。

Traceback (most recent call last):

File"/Users/nathanlakes/Desktop/Q12.py", line 15, in

total += value

Python for?TypeError: unsupported operand type(s) for +=: 'int' and 'str'

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

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

尝试更改此行:

number_list.append(num)

python循环结构、对此:

number_list.append(int(num))

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

number_string = input("Enter some numbers:")

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

for loop python、但请注意,如果您输入类似"123abc"的内容,您的程序将崩溃。如果您有兴趣,请查看处理异常,特别是ValueError。

我同意这是一个有效的解决方案,但基于命名,将其添加到名为"number_list"的列表时将其转换为整数更有意义。 否则他每次使用数字时都需要施放。

同意,我编辑了我的帖子。

所以你建议当我附加到列表时,我追加int()

@Nate是的,这样就可以将字符串转换为整数,可以将其添加到total

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

number_string = input("Enter some numbers:")

print  sum(int(n) for n in number_string)

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

>>> number_string ="123"

python eval、>>> sum(int(n) for n in number_string)

6

>>>

编辑:

number_string = input("Enter some numbers:")

python list。print  sum(map(int, number_string))

或者sum(map(int, number_string))。

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

python教程、>>> s = input('--> ')

--> Monty Python's Flying Circus

>>> s

"Monty Python's Flying Circus"

因此,当您在示例的第一行中执行输入时,您基本上会获得字符串。

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

total = total + int(value)

关于调试:

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

做类型(num)会告诉你它是一个字符串。显然无法添加string和int。

`

将行更改为:

total += int(value)

要么

total = total + int(value)

附:两个代码行都是等价的。

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://808629.com/70859.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 86后生记录生活 Inc. 保留所有权利。

底部版权信息