Python如何将此for循环转换为while循环

时间:2012-09-26 22:37:49

标签: python

  

可能重复:
  Converting a for loop to a while loop

我有一个for循环,我让我想知道如何写,所以它可以使用while循环。

def scrollList(myList):
    negativeIndices=[]
    for i in range(0,len(myList)):
        if myList[i]<0:
            negativeIndices.append(i)
    return negativeIndices

到目前为止,我有这个

def scrollList2(myList):
    negativeIndices=[]
    i= 0
    length= len(myList)
    while i != length:
        if myList[i]<0:
            negativeIndices.append(i)
            i=i+1

    return negativeIndices

2 个答案:

答案 0 :(得分:6)

嗯,你快到了。就像这样:

def scrollList2(myList):
    negativeIndices=[]
    i= 0
    length= len(myList)
    while i != length:
        if myList[i]<0:
            negativeIndices.append(i)
        i=i+1

    return negativeIndices

您遇到的问题是必须在每次迭代时增加循环索引。您只是在找到负值时才递增。


但最好是for循环,而for循环过于复杂。我会这样写:

def scrollList(myList):
    negativeIndices=[]
    for index, item in enumerate(myList):
        if item<0:
            negativeIndices.append(index)
    return negativeIndices

答案 1 :(得分:2)

嗯,对于一个,你的增量器i应该总是更新,而不是仅仅在你满足条件时。只在if语句中执行此操作意味着当您看到可返回元素时,您才会前进,因此如果您的第一个元素不符合您的条件,您的函数将会挂起。哎呀。这会更好:

def scrollList2(myList):
    negativeIndices=[]
    i= 0
    length= len(myList)
    while i != length:
        if myList[i]<0:
            negativeIndices.append(i)
        i=i+1

    return negativeIndices