-1

可能重复:
将 for 循环转换为 while 循环

我有一个 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
4

2 回答 2

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
于 2012-09-26T22:41:15.250 回答
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
于 2012-09-26T22:41:23.343 回答