简体   繁体   English

如何以更优雅的Pythonic方式组织这个循环

[英]How to organize this loop in a more elegant Pythonic way

So I have a function which reduces some dataset, and returns the number of elements removed. 所以我有一个减少一些数据集的函数,并返回删除的元素数。 I have to stop applying it once the number of items reduced during the function's operation is zero. 一旦在功能操作期间减少的项目数为零,我必须停止应用它。 Currently I've got this: 目前我有这个:

num_removed = reduction_pass(dataset)
while num_removed > 0:
    num_removed = reduction_pass(dataset)

but these two variable assignments kind of get to me. 但是这两个变量赋值给了我。 Is there a more elegant way to write this? 是否有更优雅的方式来写这个?

I assume you don't actually need the final return value, as I assume it indicates the number of removed elements, which will obviously always be 0 on the last pass. 我假设你实际上并不需要最终的返回值,因为我认为它表示已删除元素的数量,在最后一次传递中显然总是为0。

The simple-is-better-than-complex way: 简单易于复杂的方式:

while reduction_pass(dataset) > 0: pass

The showing-off, obviously-not-serious way: 炫耀,显然不严肃的方式:

from itertools import *
list(takewhile(lambda x: x > 0, starmap(reduction_pass, repeat((dataset,)))))

You can get an iterator with 你可以得到一个迭代器

it = iter(lambda: reduction_pass(dataset), 0)

which, on every step, calls the given function and stops when 0 is retrieved. 在每一步,它调用给定的函数,并在检索到0时停止。

With this iterator, you can do 有了这个迭代器,你就可以做到

for num_removed in it:
    do_whatever()

Yes, Python doesn't allow statements inside the conditions control structures. 是的,Python不允许条件控制结构中的语句。 It has its pluses, and it has its minuses. 它有它的优点,它有它的缺点。

If you find the two var assignments so annoying, maybe this is better: 如果你发现两个var赋值很烦人,也许这样更好:

while True:
  num_removed = reduction_pass(dataset)
  if num_removed <= 0:
    break

Although generally I don't think you should worry about it too much. 虽然一般我认为你不应该担心它太多。

The most obvious way to me is: 对我来说最明显的方法是:

num_removed = None
while num_removed is None or num_removed > 0:
    num_removed = reduction_pass(dataset)

A while loop with a break in it is usually simplest and best, however assuming that when you said to loop while num_removed > 0 you might actually have meant num_removed != 0 , here's a fairly clean alternative: 一个带有中断的while循环通常是最简单和最好的,但假设当你说num_removed > 0时循环时你实际上可能意味着num_removed != 0 ,这里是一个相当干净的选择:

for num_removed in iter(lambda: reduction_pass(dataset), 0):
    pass

That only makes sense of course if you actually need the intermediate values of num_removed for something inside the loop body. 如果你真的需要num_removed的中间值用于循环体内的某些东西,那当然才有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM