Python:使用“while”循环返回列表中小于目标值的值的索引

时间:2012-09-28 21:49:04

标签: python-2.7 while-loop

程序应该将列表作为输入,并返回小于0的值的索引。

但是,我不允许使用for循环。我必须使用while循环来完成它。

例如,如果我的函数名为findValue(list)而我的列表是[-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

2 个答案:

答案 0 :(得分: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]))

答案 1 :(得分:0)

尝试一下:

def findValue(list):
    res=[]
    for i in list:
        if i < 0:
            res.append(list.index(i))
    return res