【问题标题】:How can I convert to while loop如何转换为while循环
【发布时间】:2018-10-30 04:03:23
【问题描述】:

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

【问题讨论】:

  • 为什么要用while循环来写这个。作为for循环非常好
  • 当然,for循环很好。但我不知道。我只是想试试他们两个。只是为了改进。
  • 虽然意图是好的,但你不会尝试使用while 循环来实现len,因为如果你超出范围,你会得到while list[i] 的IndexError
  • 您需要通过说 while i < len(list) 来绑定您的 while 条件,但您只是在那里使用 len。这不是练习while 循环的最佳练习
  • 好的,谢谢您的关注。

标签: python loops while-loop


【解决方案1】:

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

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

【讨论】:

  • 我以为他不想使用 len 函数,因为他正在尝试自己实现它?
  • @eol 好的,添加了一个检查有效索引的功能。
  • 这绝对是一个更好的解决方案,我会删除我的:)
【解决方案2】:
def length(items) :
    idx = 0
    try:
        while True:
            _ = items[idx] 
           idx += 1
    except IndexError:
        return idx

【讨论】:

    【解决方案3】:

    如果您真的想将此代码转换为 while 循环,您可以随时执行以下操作:

    def length_itr_whl(list):
        total = 0
        i = 0
        while list[i:i+1]:
            total = total + 1
            i = i + 1
        return total
    
    print length_itr_whl([1,2,3,4,5]) # prints 5
    print length_itr_whl([]) # prints 0
    

    这使用 Python 中的列表切片机制,不需要任何try-block。当索引超出范围时,结果将是 [](一个空列表),在 Python 中计算为 False

    但是,为什么不直接使用 Python 中内置的len-函数呢?

    【讨论】:

    • vov 这正是我想要的。但是 list[i:i+1] 是 list[0:1] 怎么会发生?我不明白这里的事件。顺便说一句,我知道切片是什么意思。但在这里,我没有得到它的事件。实际上是为了好奇。只是我想尝试提高我的技能。我是代码新手。
    • while-loop 只需要一个可以计算为TrueFalse 的表达式。在 Python 中,一个空列表 ([]) 的计算结果为 False,导致 while 循环停止。当list[i:i+1] 中的索引超出范围时,您会得到一个空列表。
    【解决方案4】:

    试试这个:

    list=[1,2,3,4,5]
    total = 0
    while total != len(list):
        total +=1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-19
      • 2015-02-16
      • 1970-01-01
      • 2021-05-22
      • 1970-01-01
      • 2021-02-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多