何时使用“while"或“为"在 Python 中 [英] When to use "while" or "for" in Python

查看:21
本文介绍了何时使用“while"或“为"在 Python 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现什么时候应该在 Python 中使用 while 循环或 for 循环的问题.看起来人们更喜欢使用 for 循环(更少的代码行?).有什么具体情况我应该使用其中一种吗?这是个人喜好的问题吗?到目前为止,我读过的代码让我觉得它们之间存在很大差异.

解决方案

是的,while 和 for 之间存在巨大差异.

for 语句遍历集合或可迭代对象或生成器函数.

while 语句只是循环,直到条件为 False.

这不是偏好.这是你的数据结构的问题.

通常,我们将要处理的值表示为 range(实际列表)或 xrange(生成值)(Edit:在 Python 3 中,range 现在是一个生成器,其行为类似于旧的 xrange 函数.xrange 已从 Python 3 中删除).这为我们提供了为 for 语句量身定制的数据结构.

然而,一般来说,我们有一个现成的集合:一个集合、元组、列表、映射甚至一个字符串都已经是一个可迭代的集合,所以我们只需使用一个 for 循环.>

在某些情况下,我们可能希望为我们完成一些函数式编程处理,在这种情况下,我们可以将该转换应用为迭代的一部分.sortedenumerate 函数对自然适合 for 语句的可迭代对象应用转换.

如果您没有可迭代的整洁数据结构,或者您没有驱动处理的生成器函数,则必须使用 while.

I am finding problems in when I should use a while loop or a for loop in Python. It looks like people prefer using a for loop (less code lines?). Is there any specific situation which I should use one or the other? Is it a matter of personal preference? The codes I have read so far made me think there are big differences between them.

解决方案

Yes, there is a huge difference between while and for.

The for statement iterates through a collection or iterable object or generator function.

The while statement simply loops until a condition is False.

It isn't preference. It's a question of what your data structures are.

Often, we represent the values we want to process as a range (an actual list), or xrange (which generates the values) (Edit: In Python 3, range is now a generator and behaves like the old xrange function. xrange has been removed from Python 3). This gives us a data structure tailor-made for the for statement.

Generally, however, we have a ready-made collection: a set, tuple, list, map or even a string is already an iterable collection, so we simply use a for loop.

In a few cases, we might want some functional-programming processing done for us, in which case we can apply that transformation as part of iteration. The sorted and enumerate functions apply a transformation on an iterable that fits naturally with the for statement.

If you don't have a tidy data structure to iterate through, or you don't have a generator function that drives your processing, you must use while.

这篇关于何时使用“while"或“为"在 Python 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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