如何在 Python 中使用 C 风格的 for 循环? [英] How do I use a C-style for loop in Python?
问题描述
我想使用传统的 C 风格的 for 循环Python.我想遍历字符串的字符,但也知道它是什么,并且能够跳过字符(例如 i =
5 代码中的某处).
I want to use the traditional C-style for loop in Python. I want to loop through characters of a string, but also know what it is, and be able to jump through characters (e.g. i =
5 somewhere in the code).
for
with range
没有给我实际 for 循环的灵活性.
for
with range
doesn't give me the flexibility of an actual for loop.
推荐答案
简单的答案是,Python 中没有简单、精确的 C 语言 for
语句的等价物.使用带有范围的 Python for
语句涵盖的其他答案.如果您希望能够在循环中修改循环变量(并使其影响后续迭代),则必须使用 while
循环:
The simple answer is that there is no simple, precise equivalent of C's for
statement in Python. Other answers covered using a Python for
statement with a range. If you want to be able to modify the loop variable in the loop (and have it affect subsequent iterations), you have to use a while
loop:
i = 0
while i < 7:
if someCondition(i):
i = 5
i += 1
但在该循环中,continue
语句的效果与 C for
循环中的 continue
语句的效果不同.如果你想让 continue
像在 C 中那样工作,你必须加入一个 try
/finally
语句:
But in that loop, a continue
statement will not have the same effect that a continue
statement would have in a C for
loop. If you want continue
to work the way it does in C, you have to throw in a try
/finally
statement:
i = 0
while i < 7:
try:
if someCondition(i):
i = 5
elif otherCondition(i):
continue
print 'i = %d' % i
finally:
i += 1
如您所见,这非常难看.您应该寻找一种更 Pythonic 的方式来编写您的循环.
As you can see, this is pretty ugly. You should look for a more Pythonic way to write your loop.
这刚刚发生在我身上......有一个复杂的答案,它可以让您像 C 样式循环一样使用普通的 Python for
循环,并允许通过编写自定义来更新循环变量迭代器.我不会将这个解决方案推荐给任何真正的程序,但它是一个有趣的练习.
This just occurred to me... there is a complicated answer that lets you use a normal Python for
loop like a C-style loop, and allows updating the loop variable, by writing a custom iterator. I wouldn't recommend this solution for any real programs, but it's a fun exercise.
C 风格"for 循环示例:
Example "C-style" for loop:
for i in forrange(10):
print(i)
if i == 3:
i.update(7)
输出:
0
1
2
3
8
9
诀窍是 forrange
使用了 int
的子类,它添加了一个 update
方法.forrange
的实现:
The trick is forrange
uses a subclass of int
that adds an update
method. Implementation of forrange
:
class forrange:
def __init__(self, startOrStop, stop=None, step=1):
if step == 0:
raise ValueError('forrange step argument must not be zero')
if not isinstance(startOrStop, int):
raise TypeError('forrange startOrStop argument must be an int')
if stop is not None and not isinstance(stop, int):
raise TypeError('forrange stop argument must be an int')
if stop is None:
self.start = 0
self.stop = startOrStop
self.step = step
else:
self.start = startOrStop
self.stop = stop
self.step = step
def __iter__(self):
return self.foriterator(self.start, self.stop, self.step)
class foriterator:
def __init__(self, start, stop, step):
self.currentValue = None
self.nextValue = start
self.stop = stop
self.step = step
def __iter__(self): return self
def next(self):
if self.step > 0 and self.nextValue >= self.stop:
raise StopIteration
if self.step < 0 and self.nextValue <= self.stop:
raise StopIteration
self.currentValue = forrange.forvalue(self.nextValue, self)
self.nextValue += self.step
return self.currentValue
class forvalue(int):
def __new__(cls, value, iterator):
value = super(forrange.forvalue, cls).__new__(cls, value)
value.iterator = iterator
return value
def update(self, value):
if not isinstance(self, int):
raise TypeError('forvalue.update value must be an int')
if self == self.iterator.currentValue:
self.iterator.nextValue = value + self.iterator.step
这篇关于如何在 Python 中使用 C 风格的 for 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!