python-3.x - while 循环时索引错误 : list index out of range (Python beginner,)

标签 python-3.x

我正在尝试创建一个接受列表作为输入参数的函数。我将使用 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/

相关文章:

python - 分配一个 pandas dataframe NULL=0, non-NULLvalue=1

python - 我在 python 中使用 pyttsx3 时收到 "member not found"错误

python - 重组程序以使用 asyncio

python-3.x - 如何在 python 中模拟 sendgrid web api v.3 方法

python脚本高级调度

python-3.x - Plotly 无法为多个跟踪器返回选定数据点的信息

python-3.x - PyZMQ Dockerized pub sub - sub不会收到消息

python-3.x - 音频 .wav 文件的二进制分类

python - 安装gobject模块?

python-3.x - Plotly Dash-单击时将注释添加到散点图