首页 > 解决方案 > 如何转换为while循环

问题描述

我写了这段代码。这就像 len() 函数。

def length_itr_for(list):
    total = 0
    for i in list:
        total += 1
    return total

print length_itr_for([1,2,3,4,5,6,7,8])

输出是;8. 因为在这个列表中,有 8 个值。所以 len 在这个列表中是 8。

但我不知道如何用while循环编写这段代码?

while list[i]: etc... 我虽然做了一些事情,但我不知道我应该在这里写什么。

编辑:实际上我也试过这段代码。但这不是好的代码。刚刚尝试过,但没有奏效。

def length_itr_whl(list):
    total = 0
    i = 0
    while list[i]:
        total = total + 1
        i = i + 1
    return total

print length_itr_whl([1,2,3,4,5])

标签: pythonloopswhile-loop

解决方案


您可以编写一个函数来测试索引是否在列表的范围内:

def validIndex(l, i):
    try:
        _ = l[i]
    except IndexError:
        return False
    return True

我从If list index exists, do X

然后你可以在你的循环中使用它:

def length_itr_whl(list):
    total = 0
    index = 0
    while validIndex(list, index):
        total += 1
        index += 1
    return total

您还可以while True:在循环中使用并捕获索引错误。

def length_itr_whl(list):
    total = 0
    index = 0
    try:
        while True:
            _ = list[index]
            total += 1
            index += 1
    except IndexError:
        pass
    return total

推荐阅读