2015-09-22 38 views
1

我有一個循環:循環中可能有不穩定的步驟嗎?

result = [] 
list = ['a', 'b', 'c', 'd', 'e', 'f'] 
start = 2 
step = 5 
end = start + step*len(list) 
for i in range(start, end, step): 
    result.append(list[i%len(list)]) 
print result 

在這種情況下,結果將是:

['c', 'b', 'a', 'f', 'e', 'd'] 

但是,讓我們說,我想要的結果是(起始索引更改爲1):

['b', 'a', 'd', 'c', 'f', 'e'] 

我如何在每個循環之後進行階躍變更,以便在第一個循環中步驟是5,在下一個循環中它是3,然後是5,等等。

+0

...與另一個循環? – jonrsharpe

+0

so ...你想生成數字序列:'3','8','11','16',...? – mgilson

+0

將你的代碼放入一個函數中,並將該步驟作爲參數傳遞? – dsh

回答

1

一個非常簡單的解決方案是使用一個單獨的變量來指示從列表中獲取的索引,並根據您的步驟手動增加該索引。示例 -

lst = ['a', 'b', 'c', 'd', 'e', 'f'] 
i = 1 
new_lst = [] 
for j in range(len(lst)): 
    new_lst.append(lst[i%len(lst)]) 
    if j%2 == 0: 
      i += 5 
    else: 
      i += 3 

演示 -

>>> lst = ['a', 'b', 'c', 'd', 'e', 'f'] 
>>> i = 1 
>>> new_lst = [] 
>>> for j in range(len(lst)): 
...  new_lst.append(lst[i%len(lst)]) 
...  if j%2 == 0: 
...    i += 5 
...  else: 
...    i += 3 
... 
>>> new_lst 
['b', 'a', 'd', 'c', 'f', 'e'] 

而且,你不應該使用list作爲變量名,它陰影內置功能list,定義你list變量之後,這意味着,你不會能夠使用內置功能list()

3

你可以寫自己的發電機這樣的事情:

​​

和使用看起來像:

for i in super_range(start, end, (5, 3)): 
    result.append(list[i%len(list)]) 
1

根據你想要做的,而不是迭代和改變什麼您可以使用和python內置函數或itertools模塊的步驟。在這種情況下,你可以起訴zip功能和iterools.chain

>>> list(chain.from_iterable((j,i) for i,j in zip(li[0::2],li[1::2]))) 
['b', 'a', 'd', 'c', 'f', 'e'] 

在其他情況下,你可能需要使用一些功能,如itertools.islice()zip_longest

0

它是一個while循環而不是for循環?即一個是當你不知道在這個循環周圍需要多少次旅行時,但有一個很好的理由相信某件事會終止循環。大綱代碼:

i, inc, newlst = 1, 2, [] 
while i < len(lst) and i >= 0: 
    newlst.append(lst[i]) 
    # if some_condition: inc = some_new_value 
    i += inc 

類似的結構採用與while True內部if something: break

發電機(上述)是另一種方法。