Reputation: 4372
How can I perform below code in python I am new to python and getting troubled, please could someone help
objects = [............] // Array
for (i=0; i<objects.length(); i++) {
if(readElement(objects[i])){
//do something
} else {
i--; // so that same object is given in next iteration and readElement cant get true
}
}
Upvotes: 2
Views: 2107
Reputation: 3228
I was looking for the same thing, but I ended up writing a while
loop, and manage the index myself.
That said, your code can be implemented in Python as:
objects = [............] # Array
idx = 0
while idx < len(objects):
if readElement(objects[idx]):
# do hacky yet cool stuff
elif idx != 0:
idx -= 1 # THIS is what you hoped to do inside the for loop
else:
# some conditions that we haven't thought about how to handle
Upvotes: 0
Reputation: 520
Your code is iterating through a list of objects and repeats "readElement" until it returns "True", in which case you call "do something". Well, you could just write that down:
for object in objects:
while not readElement(object): pass
dosomething()
[Edit: the first version of this answer inverted the logic, sorry]
Upvotes: -1
Reputation: 398
You can try this out
objects = ["ff","gg","hh","ii","jj","kk"] # Array
count =0
for i in objects: # (i=0; i<objects.length(); i++) {
if i:
print i
else :
print objects[count-1]
count =+1
Upvotes: 0
Reputation: 4163
Have you considered using recursion?
def func(objects,i):
if i == len(objects):
return
if readElement(objects[i]){
#do something
func(objects,i+1)
else
func(objects,i)--; # so that same object is given in next iteration and readElement cant get true
}
objects = [............] # list
func(objects,0)
Else, you can do this(very non-Pythonic, but using for
loops only as you requested):
objects = [............] # Array
func(objects,0)
M = 10E6 # The maximum number of calls you think is needed to readElement(objects[i])
for i in xrange(objects)
for j in xrange(M):
if readElement(objects[i]):
#do something
break
Upvotes: 2