在Python中验证列表元素

2024-09-25 00:29:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着验证输入的每个元素,以确保没有少于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

Tags: andname名称loop元素inputnamescounter
1条回答
网友
1楼 · 发布于 2024-09-25 00:29:19

在Python中,列表索引从零开始。所以nameList的第一个索引是0,而不是{}。因此,因为您将counter初始化为1,然后尝试索引nameList,Python引发了一个IndexError。在

但是,您的代码仍然存在问题。做nameList[counter] > 2不是比较nameList中索引counter处的字符串长度。它只是简单地将字符串本身与整数2进行比较,这实际上没有意义。您需要使用len()内置函数来获取字符串的长度:

counter = 0

while counter <=20:
    ...
    if len(nameList[counter]) < 2:
        ...
    ...

相关问题 更多 >