我有一个for循环,我让我想知道如何写,所以它可以使用while循环。
def scrollList(myList):
negativeIndices=[]
for i in range(0,len(myList)):
if myList[i]<0:
negativeIndices.append(i)
return negativeIndices
到目前为止,我有这个
def scrollList2(myList):
negativeIndices=[]
i= 0
length= len(myList)
while i != length:
if myList[i]<0:
negativeIndices.append(i)
i=i+1
return negativeIndices
答案 0 :(得分:6)
def scrollList2(myList):
negativeIndices=[]
i= 0
length= len(myList)
while i != length:
if myList[i]<0:
negativeIndices.append(i)
i=i+1
return negativeIndices
您遇到的问题是必须在每次迭代时增加循环索引。您只是在找到负值时才递增。
但最好是for
循环,而for
循环过于复杂。我会这样写:
def scrollList(myList):
negativeIndices=[]
for index, item in enumerate(myList):
if item<0:
negativeIndices.append(index)
return negativeIndices
答案 1 :(得分:2)
嗯,对于一个,你的增量器i
应该总是更新,而不是仅仅在你满足条件时。只在if
语句中执行此操作意味着当您看到可返回元素时,您才会前进,因此如果您的第一个元素不符合您的条件,您的函数将会挂起。哎呀。这会更好:
def scrollList2(myList):
negativeIndices=[]
i= 0
length= len(myList)
while i != length:
if myList[i]<0:
negativeIndices.append(i)
i=i+1
return negativeIndices