700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > python列表for循环 加入新列表_关于python:使用for循环在列表中添加值

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

时间:2024-03-13 05:03:00

相关推荐

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

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

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

total += value

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

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

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

尝试更改此行:

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"的内容,您的程序将崩溃。如果您有兴趣,请查看处理异常,特别是ValueError。

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

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

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

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

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

number_string = input("Enter some numbers:")

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

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

>>> number_string ="123"

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

6

>>>

编辑:

number_string = input("Enter some numbers:")

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:

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

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。