Python 2.7 Python:使用“返回”返回列表中小于目标值的值的索引;而";环
程序应该以列表作为输入,并返回小于0的值的索引 但是,我不允许使用for循环。我必须使用while循环 例如,如果我的函数名为findValue(list),而我的list为[-3,7,-4,3,2,-6],那么它看起来像这样:Python 2.7 Python:使用“返回”返回列表中小于目标值的值的索引;而";环,python-2.7,while-loop,Python 2.7,While Loop,程序应该以列表作为输入,并返回小于0的值的索引 但是,我不允许使用for循环。我必须使用while循环 例如,如果我的函数名为findValue(list),而我的list为[-3,7,-4,3,2,-6],那么它看起来像这样: >>>findValue([-3,7,-4,3,2,-6]) 会回来吗 [0, 2, 5] 到目前为止,我已经尝试: def findValue(list): under = [] length = len(list) wh
>>>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
def findValue(列表):
低于=[]
长度=长度(列表)
当长度>0时:
如果列表中的x<0:#问题显然就在这里。但它给你
在.append(x)下#了解我正在尝试做什么
长度=长度-1
返回负数
我对您的代码做了一些小改动。基本上,我使用变量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]))
def findValue(列表):
结果=[]
i=0
长度=长度(列表)
而我<长度:
x=列表[i]
如果x<0:
结果.追加(i)
i=i+1
返回结果
打印(findValue([-3,7,-4,3,2,-6]))
试试这个:
def findValue(list):
res=[]
for i in list:
if i < 0:
res.append(list.index(i))
return res
def findValue(列表):
res=[]
对于列表中的i:
如果i<0:
res.append(列表索引(i))
返回res
刚刚重新编辑了我原来的postperfect,这正是我想要的解决方案。谢谢