2016-09-04 63 views
-2

到目前爲止還沒有找到滿意答案,因此將其作爲新問題發佈。在「for」循環中同時運行多個(即正常和反向)迭代器

我必須執行以下操作:

我有一個參數,例如test_num = 5。 現在,在一個for循環的迭代中,我希望迭代器同時向前和向後運行。

因此,作爲一個輸出,我想是這樣的:

Forward is 0, backward is 5. 
Forward is 1, backward is 4. 
Forward is 2, backward is 3. 
Forward is 3, backward is 2. 
Forward is 4, backward is 1. 

,我可以想出的唯一的事情,就是:

test_num = 5 
for j in range(test_num): 
    for i in range(test_num, 0, -1): 
     print "Forward is ", i, ", Backward is ", j 

但是,這顯然是不正確的方法。正在使用zip唯一的選擇?因爲zip只適用於如果我使用相同參數或兩個參數相等的情況。我正在尋找足夠靈活的東西。

+2

你是什麼意思有? 'zip'應該可以正常工作。 –

+0

另外,是否有意讓你的「倒退」數字不是前進數字倒過來而是偏移1? –

+0

不清楚爲什麼你不需要zip,你可以用例子來解釋 – AlokThakur

回答

1

看起來你的代碼非常好,但你只需要1個迭代器。

for x in range(5): 
    print(str(x)+'_'+str(5-x)) 

如果你真的想用兩個迭代器,請嘗試使用zip()功能這會給你正確的想法

0

for i,j in zip(range(5), range(5, 0, -1)): 
    print "Forward is {0}, backward is {1}".format(i, j) 
#Forward is 0, backward is 5. 
#Forward is 1, backward is 4. 
#Forward is 2, backward is 3. 
#Forward is 3, backward is 2. 
#Forward is 4, backward is 1. 

但是,您的具體使用情況似乎很容易給使用1迭代器:

for i in range(5) 
    print "Forward is {0}, backward is {1}".format(i, 5-i) 
#Forward is 0, backward is 5. 
#Forward is 1, backward is 4. 
#Forward is 2, backward is 3. 
#Forward is 3, backward is 2. 
#Forward is 4, backward is 1. 
0

最快解決方案:

test_num = 5 
for i in range(test_num): 
    print("Forward is %d, backward is %d."%(i, test_num-i)) 

另一個快速的解決方案(我的解決方案,如果你不會使用test_num-i表達):

test_num = 5 
for i,j in enumerate(range(test_num,0,-1)): 
    print("Forward is %d, backward is %d."%(i, j)) 

使用拉鍊(如果你想使用ZIP另一種解決方案!但是慢):

test_num = 5 
for i,j in zip(range(test_num), range(test_num, 0, -1)): 
    print("Forward is %d, backward is %d."%(i, j)) 

基準:「同樣的參數或者在兩個參數是相等的情況下,」

timeit.timeit('for i in range(5):pass', number=10000) # 0.004307041002903134 
timeit.timeit('for i,j in enumerate(range(5,0,-1)): pass', number=10000) # 0.007563826999103185 
timeit.timeit('for i,j in zip(range(5), range(5, 0, -1)): pass', number=10000) # 0.010275325999828056