Python的转换for循环变成一个while循环

问题描述:

可能重复:
Converting a for loop to a while loopPython的转换for循环变成一个while循环

我有这样的一个循环,我做我不知道我怎么会这么写它会与一个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 
+5

为什么?不,真的,为什么? –

+1

@ user1690198我会先看看循环是如何工作的 - 直接在列表上循环,而不是在一系列的痕迹上循环。 (''[index [index for index,value in enumerate(myList)if value

+1

'scrollList = lambda lst:[i for i,v in enumerate(lst)if v phihag

嗯,就快成功了。这是这样的:

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 

好,一,你的增量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