I've started learning Python a few days ago and I ran into a program while coding something.
Here's what I want to do using C++ code
number = SOME_NUMBER;
while(1) {
for(int i=number; i<sizeOfArray; i++) {
// do something
}
number = 0;
}
Basically, for the very first iteration of my for loop, I want to start i at number. Then for every other time i go through the for loop, I want to start it at 0.
My kind of hacky idea that I can think of right now is to do something like:
number = SOME_NUMBER
for i in range(0, len(array)):
if i != number:
continue
// do something
while True:
for i in range(0, len(array)):
// do something
Is this the best way or is there a better way?
what is the problem with this?
starting_num = SOME_NUMBER
while True:
for i in xrange(starting_num, len(array)):
# do code
starting_num = 0
it does exactly what you want.
however, i think there are better ways to do things especially if the solution seems "hacky".
if you gave an idea of what you wanted to do, maybe there is a better way
I don't see why you couldn't just do the same thing you are in C:
number = SOME_NUMBER
while True:
for i in range(number, len(array)):
# do something
number = 0
BTW, depending on which version of Python you're using, xrange
may be preferable over range
. In Python 2.x, range
will produce an actual list of all the numbers. xrange
will produce an iterator, and consumes far less memory when the range is large.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With