项目禁用while语句,Python标准库是否有等效循环函数?
Great question! Since you can't use the while keyword directly, there are a few clean ways to replicate your loop_while logic using Python's standard libraries or concise one-liners. Let's walk through them:
1. Standard Library Solution with itertools
You can combine itertools.accumulate and itertools.takewhile to replicate your loop behavior without using the while keyword. This is the most readable standard-library-based approach:
from itertools import accumulate, takewhile def loop_while(pred, g, f, *args, **kwargs): initial = f(*args, **kwargs) # Generate the sequence of values where the predicate holds true # accumulate creates initial, g(initial), g(g(initial)), ... valid_values = takewhile(pred, accumulate([initial], lambda current, _: g(current))) # Extract the last valid value (or stay with initial if no values passed the predicate) last_valid = None for last_valid in valid_values: pass # If there were valid values, apply g one final time to reach the terminating value # Otherwise, return initial (since pred(initial) was already False) return g(last_valid) if last_valid is not None else initial
Testing your example:
loop_while(lambda r: r != 0, lambda v: v - 1, lambda: 5) # Returns 0
2. One-Liner (No Imports)
If you want a concise one-liner without relying on external libraries, you can use a generator expression with next() and a mutable object to track the current value. It's a bit clever, but works:
# Your example parameters pred = lambda r: r != 0 g = lambda v: v - 1 f = lambda: 5 result = next( current[0] for current in [[f()]] while pred(current.__setitem__(0, g(current[0])) or current[0]) ) # result equals 0
How this works:
- We use a list
currentto hold the mutable value (since integers are immutable in Python) current.__setitem__(0, g(current[0]))updates the value and returnsNoneor current[0]gives us the new value to check againstpred- The generator runs until
predreturns False, thennext()pulls the final terminating value
3. Recursive Approach (Not Recommended for Large Iterations)
You could also use recursion, but note this will hit Python's recursion depth limit for large sequences (e.g., if your initial value was 10,000):
def loop_while(pred, g, f, *args, **kwargs): res = f(*args, **kwargs) return loop_while(pred, g, lambda: g(res)) if pred(res) else res
Testing this with your example also returns 0, but avoid it for large loops to prevent a RecursionError.
内容的提问来源于stack exchange,提问作者uspectaculum

