2012-09-28 61 views
0

程序應將輸入列表作爲輸入並返回小於0的值的索引。Python:使用「while」循環返回列表中值小於目標值的索引

但是,我不允許使用for循環。我必須用while循環來做。

例如,如果我的功能被命名爲findValue(名單)和我的名單爲[-3,7,-4,3,2,-6],它會是這個樣子:

>>>findValue([-3,7,-4,3,2,-6]) 

將返回

[0, 2, 5] 

到目前爲止,我曾嘗試:

def findValue(list): 
    under = [] 
    length = len(list) 
    while length > 0: 
     if x in list < 0:  #issues are obviously right here. But it gives you 
      under.append(x)  #an idea of what i'm trying to do 
     length = length - 1 
    return negative 
+0

剛剛重新編輯我的原始文章 – user1707398

回答

0

我做了一些小的改動你的代碼。基本上我使用變量i來表示在給定迭代中元素x的索引。

def findValue(list): 
    result = [] 
    i = 0 
    length = len(list) 
    while i < length: 
     x = list[i] 
     if x < 0:  
      result.append(i) 
     i = i + 1 
    return result 

print(findValue([-3,7,-4,3,2,-6])) 
+0

完美,正是我所尋找的解決方案。謝謝 – user1707398