什么时候使用"while"?或“用于"在Python中 [英] When to use "while" or "for" in Python
问题描述
我在何时应该在Python中使用while
循环或for
循环时发现了问题.人们似乎更喜欢使用for
循环(更少的代码行?).我是否应该使用一种或另一种特定情况?这是个人喜好吗?到目前为止,我读过的代码使我觉得它们之间有很大的差异.
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.
推荐答案
是的,while和for之间存在巨大差异.
Yes, there is a huge difference between while and for.
for 语句遍历集合或可迭代对象或生成器函数.
The for statement iterates through a collection or iterable object or generator function.
while 语句仅循环执行,直到条件为False.
The while statement simply loops until a condition is False.
这不是首选项.这是关于您的数据结构是一个问题.
It isn't preference. It's a question of what your data structures are.
通常,我们将要处理的值表示为range
(实际列表)或xrange
(生成值).这为我们提供了一个为 for 语句量身定制的数据结构.
Often, we represent the values we want to process as a range
(an actual list), or xrange
(which generates the values). This gives us a data structure tailor-made for the for statement.
但是,通常,我们有一个现成的集合:一个集合,元组,列表,映射甚至是一个字符串已经是一个可迭代的集合,因此我们只需使用 for 循环即可.
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.
在某些情况下,我们可能希望为我们完成一些功能编程处理,在这种情况下,我们可以将该转换应用为迭代的一部分. sorted
和enumerate
函数对可迭代的转换应用转换,该转换自然符合 for 语句.
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.
如果您没有整齐的数据结构来循环访问,或者没有生成器函数来驱动处理,则必须在 while 期间使用.
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屋!