2012-09-28 62 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