【问题标题】:Using a for loop to add values in a list [duplicate]使用 for 循环在列表中添加值 [重复]
【发布时间】:2013-04-24 05:28:21
【问题描述】:

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

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

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

    尝试更改此行:

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

    【讨论】:

    • 我同意这是一个可行的解决方案,但根据命名,将其添加到名为“number_list”的列表时将其转换为整数更有意义。否则,他每次使用这些数字时都需要投射。
    • 同意,我已经编辑了我的帖子。
    • 所以你建议当我追加到列表时,我追加 int()
    • @Nate 是的,这样您就可以将字符串转换为整数,可以将其添加到total
    【解决方案2】:

    这里是关于 Python 3 中 input 的官方文档

     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"
    

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

    现在你需要将这些 string 转换为 int 才能进行汇总。所以你基本上会这样做:

    total = total + int(value)
    

    关于调试:

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

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

    `

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • sum(map(int, number_string))
      【解决方案4】:

      将行改为:

      total += int(value)
      

      total = total + int(value)
      

      附:两行代码是等价的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-06-20
        • 1970-01-01
        • 1970-01-01
        • 2021-06-04
        • 2021-01-12
        • 1970-01-01
        • 2016-09-29
        相关资源
        最近更新 更多