如何将 Python 中的这个 for 循环转换为 while 循环

2024-04-18 00:25:03 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
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

到目前为止我有这个

^{2}$

Tags: toinloopforlenifdefrange
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

好吧,你快到了。就像这样:

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循环过于复杂。我会这样写:

^{pr2}$

相关问题 更多 >

    热门问题