【问题标题】:Need Help Dealing with inputs需要帮助处理输入
【发布时间】:2022-07-20 00:45:31
【问题描述】:

初学者的问题,所以我遇到了这个问题,我在不同的行中收到了很多输入,例如:

Inputs:
1
2
0
2
1

我想对它们求和或将它们存储在任何类型的列表中以便稍后对它们求和,我该怎么做?

我的意思是,我可以为每个变量存储一个变量,例如:

a1 = int(input())
a2 = int(input())
ax = int(input())
....
and then 
result = a1+a2+ax...
print(result)

但这不切实际。有人可以向我解释如何将它们存储和汇总到一个列表中吗?

我觉得我也可以这样做

    x = int(input())
and use
    x += x    

【问题讨论】:

    标签: python list input


    【解决方案1】:

    只需使用 python 列表:

    inputlist = []
    
    for i in range(5):
        inputlist.append(int(input))
    
    result = sum(inputlist)
    

    注意,我只是把 5 放在那里要求 5 个值。询问任何你想要的输入。

    【讨论】:

      【解决方案2】:

      您可以使用 while 循环或 for 循环。如果您在变量x 中预先提供了输入的数量,则可以从 for 循环开始。

      x = int(input("Number of Inputs> "))  # If you know the certain number of inputs
                                            # that you are going to take, you can directly replace them here.
      answer = 0
      
      for i in range(x):
          answer += int(input())
      
      print("Answer is", answer)
      

      如果您事先不知道输入的数量,您可以实现一个 while 循环,该循环将接受输入,直到给出非整数输入。

      answer = 0
      while True:
          x = input()
          try:
              x = int(x)  # Tries to convert the input to int
          except:  # If an error occurs, ie, the input is not an integer.
              break   # Breaks the loop and prints the answer
          
          # If all goes fine
          answer += x
      
      print("Answer is", answer)
      

      【讨论】:

        【解决方案3】:

        我也是初学者,但我想出了一个解决方案:

        new_list = []
        
        for entry in range(10):
            x = int(input())
            new_list.append(x)
        
        print(sum(new_list))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-10-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-08-10
          • 1970-01-01
          相关资源
          最近更新 更多