python - 如何转换为 while 循环

标签 python loops while-loop

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

关于python - 如何转换为 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50432901/

相关文章:

python - list.append 的意外行为

jquery - 如何在不使用循环的情况下突出显示 HTML 表格列?

javascript - 我想知道while循环中要写什么条件

python - 由于未安装包轮,因此无法构建轮子

python - Python KeyError 中哪个键失败?

python - python中两个数组(不同大小)之间可能的唯一组合?

java - 迭代所有不为空的槽,二维数组?

javascript - MooTools/JavaScript 变量范围

c++ - C++ 中永无止境的 while 循环,即在输入字符串 == no 时结束?

c - 输出错误,但为什么呢?