程序应该将列表作为输入,并返回小于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
答案 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