python - 将 for 循环转换为 while 循环

标签 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

最佳答案

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

for n, val in enumerate(mylist):
    if val < 0: negativeindices.append(n)

enumerate 是一个内置函数,它生成 (index, value) 形式的对序列。

您甚至可以通过以下方式以函数式风格执行此操作:

[n for n, val in enumerate(mylist) if val < 0]

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

如果您坚持使用 while 循环执行此操作,这里有一个利用 python 迭代功能的循环(您会注意到它本质上是上述循环的手动版本,但是嘿,情况总是如此,因为这就是 for 循环的用途)。:

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

关于python - 将 for 循环转换为 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12610623/

相关文章:

python - 如何管理两个线程,pynput 鼠标监听器和 while 循环?

python - 修改其他类的列表框

python - 从特定范围生成一组排序的随机数

python - 持久子进程.Popen session

python - wxPython - 如何在传入 -1 时获取小部件的 ID?

python - Python 文件中的 Unicode 解码错误

json - 引发 JSONDecodeError ("Expecting value",s,err.value)

python - 名称错误 'html' 未使用 beautifulsoup4 定义

Python3 看不到 Django

python - while True 与 while {condition}