2015-06-10 208 views
2

我怎麼能執行下面的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 
    } 
} 
+3

使用'while'循環 – nu11p01n73R

+0

感謝@ nu11p01n73R,我能做的,但不能我不使用僅環 –

+2

@SharanabasuAngadi沒有你不能。 Python的for循環使用迭代器。那些只是前進的。你永遠不能回到迭代器中。 python'i'中的 – thefourtheye

回答

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) 

否則,你可以這樣做(非常不Python的,但只使用作爲您的要求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 
+0

@Sharanabasu Angadi能解答你的問題嗎? – omerbp

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

您的代碼遍歷一系列對象並重復「readElement」,直到它返回「True」,在這種情況下,你稱之爲「做某事」。好了,你可以只寫下來:

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

[編輯:這個答案的第一個版本倒置的邏輯,對不起]

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