Skip to main content
 首页 » 编程设计

python之如何转换为 while 循环

2024年09月07日10cloudgamer

我写了这段代码。这就像 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]) 

请您参考如下方法:

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

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