在Python中验证列表元素
我试图在输入每个元素时对其进行验证,以确保没有名称少于2位。我假设不存在只有2个字符的名称。空格或姓氏无关紧要 我得到一个列表索引超出范围错误在Python中验证列表元素,python,list,validation,Python,List,Validation,我试图在输入每个元素时对其进行验证,以确保没有名称少于2位。我假设不存在只有2个字符的名称。空格或姓氏无关紧要 我得到一个列表索引超出范围错误 #The getValidateNames function takes 20 names as input,validates them, sorts list and returns list. def getValidateNames(): nameList = [] #Create empty list variable. coun
#The getValidateNames function takes 20 names as input,validates them, sorts list and returns list.
def getValidateNames():
nameList = [] #Create empty list variable.
counter = 1 #Loop counter
#Loop through and prompt for 20 names.
while counter <=20:
nameList.append(input("Please enter name #{}:".format(counter)))
if nameList[counter] < 2:
print("You have entered an invalid name.")
nameList.append(input("Please try again: "))
counter += 1
nameList.sort()
return nameList
getValidateNames函数接受20个名称作为输入,对它们进行验证,对列表进行排序并返回列表。
def getValidateNames():
nameList=[]#创建空列表变量。
计数器=1#循环计数器
#循环并提示输入20个名称。
而在Python中,计数器列表索引从零开始。因此,
nameList
的第一个索引是0
而不是1
。因此,由于您将计数器
初始化为1
,然后尝试为名称列表
编制索引,Python引发了一个索引器
但是,您的代码仍然存在问题。执行nameList[counter]>2操作并不是在nameList
中比较索引counter
处的字符串长度。它只是将字符串本身与整数2
进行比较,这实际上没有意义。您需要使用len()
内置函数获取字符串的长度:
counter = 0
while counter <=20:
...
if len(nameList[counter]) < 2:
...
...
计数器=0
而计数器为什么要在测试前追加?如果不是这样,请使用len()
函数检查字符串的大小,将名称输入为变量以存储它,然后检查其大小列表索引从零开始。但是计数器-用于索引名称列表的变量
-最初设置为1
。将计数器
初始化为0。我将计数器设置为0,我将把输入存储在变量中,验证它,如果正确,将它添加到列表中。