python循环回到for循环中的前一个元素

时间:2015-06-10 06:46:33

标签: python python-2.7 python-3.x

如何在python中执行以下代码 我是python的新手并且感到困扰,请有人帮忙

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
    }
}

4 个答案:

答案 0 :(得分:2)

你考虑过使用递归吗?

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)

否则,你可以这样做(非常非Pythonic,但只按你的要求使用for循环):

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

答案 1 :(得分:0)

你可以尝试一下

 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

答案 2 :(得分:0)

我一直在寻找相同的东西,但最后我写了一个while循环,并自己管理索引。

也就是说,您的代码可以在Python中实现:

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

答案 3 :(得分:-1)

您的代码正在迭代对象列表并重复&#34; readElement&#34;直到它返回&#34; True&#34;,在这种情况下你打电话&#34;做某事&#34;。好吧,你可以写下来:

for object in objects:
    while not readElement(object): pass
    dosomething()

[编辑:这个答案的第一个版本颠倒了逻辑,抱歉]