【问题标题】:Assigning to list in while loop for python 3在 Python 3 的 while 循环中分配给列表
【发布时间】:2014-05-09 18:55:45
【问题描述】:

我有以下一些 python 代码:

# we are going to define a list:

charList = []

#which we can use to add character's data to

i = 0

print("Please input data for your first character below: ")

while i <= 5:
    charList[i] = input("What is their name? ")
    i += 1 # increments i by 1
    charList[i] = input("\nAnd what is their strength value? ")
    i += 1
    charList[i] = input("\nAnd what is their skill value? ")
    i += 1
    print("\nThank You :)\n")
    print("Now for your second character:")

print(charList[0],charList[3])

这是针对 3.4.0 版的。

出现以下错误:

>>> 
Please input data for your first character below: 
What is their name? Chewbacca
Traceback (most recent call last):
  File "C:/Users/Peter/Documents/ARCHIVES/NEW!/Computing/task3version1.0.py", line 20, in <module>
    charList[i] = input("What is their name? ")
IndexError: list assignment index out of range
>>> 

我猜这与在 while 循环中更改 i 的值有关。关于什么是错的任何想法?谢谢你:)

【问题讨论】:

    标签: python list variables while-loop increment


    【解决方案1】:

    你为什么要在一个循环中这样做?您正在尝试重写同一个列表 5 次。

    questions = ("What is their name? ", "\nAnd what is their strength value? ", "\nAnd what is their skill value? ")
    print("Please input data for your first character below: ")
    charlist = [input(i) for i in questions]
    print("\nThank You :)\n")
    print(charList[0],charList[3])
    

    如果你想要几个字符:

    charlist = []
    questions = ("What is their name? ", "\nAnd what is their strength value? ", "\nAnd what is their skill value? ")
    print("Please input data for your first character below: ")
    for i in range(5):
        character = [input(i) for i in questions]
        charlist.append(character)
        print("\nThank You :)\n")
    print(charList[0][0],charList[3][0])
    

    【讨论】:

    • 我试图将字符的名称/特征添加到列表中,以便以后可以将它们用作变量(例如 print(charList[0], "has x Skill remaining")跨度>
    • 也许您想将它们添加到列表列表中?或者,idk,名称字典:列表。 charList[0] 应该是一个字符还是他的名字?如果是名字,你如何区分不同的字符?
    【解决方案2】:

    访问列表的索引,如charList[i],用于访问/操作列表的现有元素。由于charList 开始为空,因此没有可以访问的元素。如您所见,尝试这样做会导致超出范围错误。

    相反,您似乎想追加到列表中,如下所示:

    charList.append(input("What is their name? "))
    

    【讨论】:

    • 我也尝试过最初将列表设置为 9eg。 j = [0,0,0,0,0] 在添加新变量之前,效果也很好
    猜你喜欢
    • 1970-01-01
    • 2021-11-13
    • 2017-07-31
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    相关资源
    最近更新 更多