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

问题描述 投票:0回答:2

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

但是,我不允许用于循环。我必须使用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
python-2.7 while-loop
2个回答
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
投票

尝试一下:

def findValue(list):
    res=[]
    for i in list:
        if i < 0:
            res.append(list.index(i))
    return res
© www.soinside.com 2019 - 2024. All rights reserved.