将 for 循环转换为 while 循环 [英] Converting a for loop to a while loop

查看:80
本文介绍了将 for 循环转换为 while 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to Python and I need to convert a for loop to a while loop and I am not sure how to do it. This is what I am working with:

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

推荐答案

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

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 是一个内置函数,它生成一系列 (index, value) 形式的对.

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]

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

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.

如果你坚持使用 while 循环来做这件事,这里有一个利用了 python 的迭代工具(你会注意到它本质上是上述的手动版本,但是嘿,情况总是如此,因为这就是 for 循环的作用.:

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

这篇关于将 for 循环转换为 while 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆