首页 > 解决方案 > 索引错误:列表索引超出范围(Python 初学者,while 循环)

问题描述

我正在尝试制作一个将列表作为输入参数的函数。我将使用 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: list index out of range "

我究竟做错了什么?我在while循环中挣扎......

标签: python-3.x

解决方案


如果您确实需要 while 循环,请通过josephting查看答案。

对于您展示的示例,您不需要while循环,例如

"""
Some simple functions
"""
def count_types_ex1(items):
    """Count types from a list"""
    counters = [0, 0]
    for item in items:
        if isinstance(item, int):
            counters[0] += 1
        elif isinstance(item, str):
            counters[1] += 1
    return counters

print(count_types_ex1([1, 2, 3, 'a', 'b', 4]))

def count_types_ex2(items):
    """Count types from a list"""
    check_type = lambda x: [int(isinstance(x, int)), int(isinstance(x, str))]
    counters = [check_type(x) for x in items]
    return sum(x[0] for x in counters), sum(x[1] for x in counters)

print(count_types_ex2([1, 2, 3, 'a', 'b', 4]))

输出:

[4, 2]
(4, 2)

推荐阅读