【问题标题】:Putting variables in the lists in Python在 Python 中将变量放入列表中
【发布时间】:2016-01-27 21:17:37
【问题描述】:

我想问一下我们如何在Python中使用变量来定义数组的大小(我的意思是列表)。我在下面写了一些代码,请你告诉我代码有什么问题? 谢谢..

   elif(op=='+') :
     size=int(input("Please enter how many numbers you want to add"))
     for x in range(0,size):
     print("Please enter the number",x+1) 
     inp=(input()) 
     num[x]=inp #<<<-----the error comes up when trying to run this expression
   for z in range(0,size):
     num[z]=num[z]+num[z+1]    
   print("The result is " , num[size])

【问题讨论】:

  • 你觉得哪里不对?缩进似乎是一个问题。
  • num 已经声明为python dict 还是列表??
  • 您是在尝试连接字符串 z 还是将 inp 中的数字作为整数相加?
  • 我想将 inp 中的数字添加为整数,并通过询问用户来制作 num 列表

标签: python list calculator


【解决方案1】:

Python 列表不是以特定大小初始化的,而是动态增长的。使用append添加元素:

size=int(input("Please enter how many numbers you want to add"))
num = [] # start with an empty list
for x in range(0,size):
    print("Please enter the number",x+1) 
    inp = input() 
    num.append(inp) # add elements

【讨论】:

  • 请注意,inpu() 的结果会将 inp 设置为字符串。
  • 感谢您的回答@Daniel。
【解决方案2】:

除了@Daniel 回答的inp 中的问题外,input() 的结果是一个字符串。因此,您的代码只会在您浏览列表时连接数字。此外,您为什么不断将串联放入列表中?此外,当进入范围时,您将追加输入的位数,但索引操作从 0 索引变为“大小”索引,这比列表中的实际值大一。

 for z in range(0,size):
     num[z]=num[z]+num[z+1]    
 print("The result is " , num[size])

因此,当 z == size -1 时,您将在尝试引用 num[z+1] 以及尝试引用 num[size] 的最终打印时获得超出范围的索引

另外,如果你要添加而不是连接输入字符串,你应该说 inp = int(input())

size=int(input("Please enter how many numbers you want to add"))
mytotal = 0
for x in range(0,size):
    # The next two could have been on one line
    myval = int(input("Please enter the number"))
    mytotal += myval #This is split for clarity
print mytotal

【讨论】:

  • 成功了,非常感谢。另外,如果我想添加浮点数,我应该输入什么而不是 int ?
  • @Ibrahim 你会输入 float()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多