The problem here is not that you need a while loop, but that you should use python for loops properly. The for loop causes iteration of a collection, in the case of your code, a sequence of integers.
for n, val in enumerate(mylist):
if val < 0: negativeindices.append(n)
enumerate
is a builtin which generates a sequence of pairs of the form (index, value)
.
You might even perform this in a functional style with:
[n for n, val in enumerate(mylist) if val < 0]
This is the more usual python idiom for this sort of task. It has the advantage that you don't even need to create an explicit function, so this logic can remain inline.
If you insist on doing this with a while loop, here's one that take advantage of python's iteration facilities (you'll note that it's essentially a manual version of the above, but hey, that's always going to be the case, because this is what a for loop is for).:
data = enumerate(list)
try:
while True:
n, val = next(data)
if val < 0: negativeindices.append(n)
except StopIteration:
return negativeindices
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…