2012-09-26 110 views
-1

可能重複:
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 <0]'') –

+1

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

回答

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 
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