我正在尝试创建一个接受列表作为输入参数的函数。我将使用 while 循环来迭代列表并跟踪列表中包含的整数和字符串的数量。这是我到目前为止所拥有的:
def usingwhileloop(mylist):
count = 0
int_total = 0
str_total = 0
while count <= len(mylist):
if isinstance(mylist[count], int) == True:
int_total = int_total + 1
elif isinstance((mylist[count]), str) == True:
str_total = str_total + 1
count = count + 1
newlist = [int_total, str_total]
return newlist
当我运行像 [1, 2, 3, “a”, “b”, 4] 这样的列表时,它应该返回 [4, 2] 但我收到以下错误:“第 51 行,在 usingwhileloop if isinstance(what[count], int) == True: IndexError:列表索引超出范围”
我做错了什么?我在 while 循环中挣扎......
最佳答案
这是因为您试图访问列表中不存在的项目。
为什么?假设我们使用此列表作为示例 -[1, 2, 3, “a”, “b”, 4]
计数从 0 开始,所以我假设您期望计数从 0 到 5。
0: 1
1: 2
2: 3
3: "a"
4: "b"
5: 4
但是,len(mylist)
是 6
所以循环将尝试访问 mylist[6]
这是不存在的。
您必须修改 while 循环以在 5 处停止。为此,while count <= len(mylist) - 1:
或while count < len(mylist):
就可以了。
关于python-3.x - while 循环时索引错误 : list index out of range (Python beginner,),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55013627/