Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中验证列表元素_Python_List_Validation - Fatal编程技术网

在Python中验证列表元素

在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

我试图在输入每个元素时对其进行验证,以确保没有名称少于2位。我假设不存在只有2个字符的名称。空格或姓氏无关紧要

我得到一个列表索引超出范围错误

#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,我将把输入存储在变量中,验证它,如果正确,将它添加到列表中。