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 (eg i = 5 somewhere in the code).
我想在python中使用传统的C风格循环。我想循环遍历字符串的字符,但也知道它是什么,并能够跳过字符(例如代码中的某处i = 5)。
for with range doesn't give me the flexibility of an actual for loop.
for range并没有给我一个实际for循环的灵活性。
6 个解决方案
#1
28
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:
简单的答案是在Python中没有简单,精确的等价C语句。使用带有范围的Python for语句涵盖了其他答案。如果您希望能够在循环中修改循环变量(并使其影响后续迭代),则必须使用while循环:
i = 0
while i < 7:
if someCondition(i):
i = 5
i += 1
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:
但是在该循环中,continue语句将不会具有与C for循环中的continue语句相同的效果。如果你想继续按照它在C中的方式工作,你必须抛出一个try / finally语句:
i = 0
while i < 7:
try:
if someCondition(i):
i = 5
elif otherCondition(i):
continue
print 'i = %d' % i
finally:
i += 1
As you can see, this is pretty ugly. You should look for a more Pythonic way to write your loop.
如你所见,这非常难看。您应该寻找更多Pythonic方式来编写循环。
UPDATE
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风格的循环一样使用普通的Python for循环,并允许通过编写自定义迭代器来更新循环变量。我不会为任何真正的程序推荐这个解决方案,但这是一个有趣的练习。
Example “C-style” for loop:
循环示例“C风格”:
for i in forrange(10):
print(i)
if i == 3:
i.update(7)
Output:
0
1
2
3
8
9
The trick is forrange
uses a subclass of int
that adds an update
method. Implementation of forrange
:
诀窍是forrange使用int的子类来添加更新方法。 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
#2
35
In C
:
for(int i=0; i<9; i+=2)
{
dosomething(i);
}
In python3
:
for i in range(0, 9, 2):
dosomething(i)
You just express the same idea in different languages.
你只是用不同的语言表达同样的想法。
#3
9
for i in range(n):
...is the Python equivalent of the C...
...是C语言的Python等价物......
for (i = 0; i < n; i++){
Or well, you can use:
或者,您可以使用:
for i in range(a, n, s):
...which is equivalent to...
......相当于......
for (i = a; i < n; i+=s){
#4
7
I provide the following entirely facetious solution by way of protest. Note that 'break' and 'continue' will not work. Also note that the loop body must not be indented.
我通过*提供以下完全滑稽的解决方案。请注意,'break'和'continue'不起作用。另请注意,循环体不得缩进。
class For:
def __init__(self, **loop_vars):
self.loop_vars = loop_vars
def __call__(self, arg):
if not hasattr(self, 'condition'):
self.condition = arg
return self
if not hasattr(self, 'update'):
self.update = arg
return self
while eval(self.condition, self.loop_vars, self.loop_vars):
exec arg in self.loop_vars
exec self.update in self.loop_vars
For(i = 1, j = 1)('i * j < 50')('i += 1; j += 1')('''
print i, j
''')
#5
4
You can do the following, given an array a:
给定数组a,您可以执行以下操作:
for i in range(len(a)):
a[i] = i
That's the closest Python can get to C-style loops.
这是最接近C语言循环的Python。
You can also give the range
command more arguments; for example,
您还可以为range命令提供更多参数;例如,
for i in range(2, len(a), 3)
对于范围内的i(2,len(a),3)
will start at i = 2, and increment it by 3 as long as the result is less than len(a).
将从i = 2开始,并且只要结果小于len(a),就将其递增3。
#6
3
The Python for
loop always has foreach semantics. You can, however, do this:
Python for循环总是具有foreach语义。但是,你可以这样做:
for i in xrange(10):
print i
This is very much like a C for loop. xrange
(or range
, as it was renamed in Python 3) is a constructor for a Python object that iterates through a range of numbers. See the docs for more information.
这非常像C for循环。 xrange(或范围,因为它在Python 3中重命名)是Python对象的构造函数,它遍历一系列数字。有关更多信息,请参阅文档。
#1
28
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:
简单的答案是在Python中没有简单,精确的等价C语句。使用带有范围的Python for语句涵盖了其他答案。如果您希望能够在循环中修改循环变量(并使其影响后续迭代),则必须使用while循环:
i = 0
while i < 7:
if someCondition(i):
i = 5
i += 1
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:
但是在该循环中,continue语句将不会具有与C for循环中的continue语句相同的效果。如果你想继续按照它在C中的方式工作,你必须抛出一个try / finally语句:
i = 0
while i < 7:
try:
if someCondition(i):
i = 5
elif otherCondition(i):
continue
print 'i = %d' % i
finally:
i += 1
As you can see, this is pretty ugly. You should look for a more Pythonic way to write your loop.
如你所见,这非常难看。您应该寻找更多Pythonic方式来编写循环。
UPDATE
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风格的循环一样使用普通的Python for循环,并允许通过编写自定义迭代器来更新循环变量。我不会为任何真正的程序推荐这个解决方案,但这是一个有趣的练习。
Example “C-style” for loop:
循环示例“C风格”:
for i in forrange(10):
print(i)
if i == 3:
i.update(7)
Output:
0
1
2
3
8
9
The trick is forrange
uses a subclass of int
that adds an update
method. Implementation of forrange
:
诀窍是forrange使用int的子类来添加更新方法。 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
#2
35
In C
:
for(int i=0; i<9; i+=2)
{
dosomething(i);
}
In python3
:
for i in range(0, 9, 2):
dosomething(i)
You just express the same idea in different languages.
你只是用不同的语言表达同样的想法。
#3
9
for i in range(n):
...is the Python equivalent of the C...
...是C语言的Python等价物......
for (i = 0; i < n; i++){
Or well, you can use:
或者,您可以使用:
for i in range(a, n, s):
...which is equivalent to...
......相当于......
for (i = a; i < n; i+=s){
#4
7
I provide the following entirely facetious solution by way of protest. Note that 'break' and 'continue' will not work. Also note that the loop body must not be indented.
我通过*提供以下完全滑稽的解决方案。请注意,'break'和'continue'不起作用。另请注意,循环体不得缩进。
class For:
def __init__(self, **loop_vars):
self.loop_vars = loop_vars
def __call__(self, arg):
if not hasattr(self, 'condition'):
self.condition = arg
return self
if not hasattr(self, 'update'):
self.update = arg
return self
while eval(self.condition, self.loop_vars, self.loop_vars):
exec arg in self.loop_vars
exec self.update in self.loop_vars
For(i = 1, j = 1)('i * j < 50')('i += 1; j += 1')('''
print i, j
''')
#5
4
You can do the following, given an array a:
给定数组a,您可以执行以下操作:
for i in range(len(a)):
a[i] = i
That's the closest Python can get to C-style loops.
这是最接近C语言循环的Python。
You can also give the range
command more arguments; for example,
您还可以为range命令提供更多参数;例如,
for i in range(2, len(a), 3)
对于范围内的i(2,len(a),3)
will start at i = 2, and increment it by 3 as long as the result is less than len(a).
将从i = 2开始,并且只要结果小于len(a),就将其递增3。
#6
3
The Python for
loop always has foreach semantics. You can, however, do this:
Python for循环总是具有foreach语义。但是,你可以这样做:
for i in xrange(10):
print i
This is very much like a C for loop. xrange
(or range
, as it was renamed in Python 3) is a constructor for a Python object that iterates through a range of numbers. See the docs for more information.
这非常像C for循环。 xrange(或范围,因为它在Python 3中重命名)是Python对象的构造函数,它遍历一系列数字。有关更多信息,请参阅文档。