将for循环转换为while循环

1 python python-3.x

我是Python的新手,我需要将for循环转换为while循环,我不知道该怎么做.这就是我正在使用的:

def scrollList(myList):
      negativeIndices = []
      for i in range(0,len(myList)):
            if myList[i] < 0:
                 negativeIndices.append(i)
      return negativeIndices
Run Code Online (Sandbox Code Playgroud)

Mar*_*cin 5

这里的问题不是你需要一个while循环,而是你应该正确地使用python for循环.对于代码,for循环会导致集合的迭代,这是一个整数序列.

for n, val in enumerate(mylist):
    if val < 0: negativeindices.append(n)
Run Code Online (Sandbox Code Playgroud)

enumerate是一个内置的,它生成一系列形式的对(index, value).

您甚至可以使用以下功能样式执行此操作:

[n for n, val in enumerate(mylist) if val < 0]
Run Code Online (Sandbox Code Playgroud)

对于这类任务,这是更常见的python习语.它的优点是您甚至不需要创建显式函数,因此该逻辑可以保持内联.

如果你坚持用while循环来做这个,这里有一个利用python的迭代工具(你会注意到它基本上是上面的手动版本,但是嘿,这总是如此,因为这是什么for循环用于):

data = enumerate(list)
try:
    while True:
        n, val = next(data)
        if val < 0: negativeindices.append(n)
except StopIteration:
    return negativeindices
Run Code Online (Sandbox Code Playgroud)