简体   繁体   English

为python 3分配while循环中的列表

[英]Assigning to list in while loop for python 3

I've got the following bit of python code: 我有以下一些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])

This is for version 3.4.0. 这适用于3.4.0版。

It comes up with the following error: 它出现以下错误:

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

I am guessing it is to do with an issue of i's value being changed while in the while loop. 我猜这是在while循环中改变i值的问题。 Any ideas as to what is wrong? 关于什么是错的任何想法? Thank you :) 谢谢 :)

Accessing indices of a list, like in charList[i] , is there to access/manipulate existing elements of the list. 访问列表的索引(如charList[i]中)可以访问/操作列表的现有元素。 Since charList starts out empty there are no elements that could be accessed. 由于charList从空开始,因此没有可访问的元素。 Trying to do so will give you an out of range error, as you have seen. 正如您所见,尝试这样做会给您带来超出范围的错误。

Instead you seem to want to append to the list, like this: 相反,你似乎想要附加到列表,如下所示:

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

Why are you trying to do it in a cycle? 你为什么要在一个周期中做这件事? You're trying to rewriting same list 5 times. 你试图重写相同的列表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])

If you want several characters: 如果你想要几个字符:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM