2014-12-06 64 views
3

所以我需要有2個值來回擺動。 第一次說2,第二次說4。從頂部重複。在Python中的振盪值

所以我寫了下面的發電機功能的作品。每次通過next調用它時,都會返回後續值,然後從頂部重複。

爲了學習,提高,不是意見,有沒有更好的辦法?在Python中似乎總有一種更好的方式,我喜歡學習它們以提高我的技能。

「主代碼」是隻是爲了顯示發生器,振盪器的例子,在使用中,且不是主要使用的振盪器。

## Main code 
go_Osci = g_Osci() 
for i in xrange(10): 
    print("Value: %i") %(go_Osci.next()) 

## Generator 
def g_Osci(): 
    while True: 
     yield 2 
     yield 4 

回答

7

是的,還有更好的辦法。 itertools.cycle是明確設計完成這個任務:

>>> from itertools import cycle 
>>> for i in cycle([2, 4]): 
...  print i 
... 
2 
4 
2 
4 
2 
4 
2 
# Goes on forever 

您還可以使用enumerate只循環一定的次數:

>>> for i, j in enumerate(cycle([2, 4])): 
...  if i == 10: # Only loop 10 times 
...   break 
...  print j 
... 
2 
4 
2 
4 
2 
4 
2 
4 
2 
4 
>>> 
+0

好東西感謝。使用我可以刪除我在實際代碼中使用的「while循環」。在Python中總是一個更好的方法。 – 2014-12-06 21:00:42

+1

@iCodez也表示他使用枚舉並在10 – Hackaholic 2014-12-06 21:06:36

+0

@Hackaholic中斷 - 呃,他沒有要求這樣做,但提及它聽起來很不錯。 – iCodez 2014-12-06 21:09:01

0

近兩年提出這個問題後,我想和大家分享什麼我最終想出了適合我的需求。使用內聯for循環來循環通過一些交替的值通常太靜態和不靈活,我所需要的。

我一直回到我的發生器解決方案,因爲它證明在我的應用程序中更加靈活 - 我可以隨時隨地從我的腳本中調用next()

我然後打在我的發電機使用cycle。在實例開始時,通過使用所需值列表「啓動」發生器,我可以在腳本中的任何位置訪問需要的交替值。我也可以根據需要用不同的值「填充」更多的實例。

的額外好處是,底層代碼被一般化,並且因此能夠被視爲可導入模塊。

我稱這種構造爲使用發生器產生交替值「振盪器」。

我希望這會對未來的人有好處。

的Python 2.7.10

# Imports # 
from __future__ import print_function 
from itertools import cycle 

    # Generators 
def g_Oscillator(l_Periods): 
"""Takes LIST and primes gen, then yields VALUES from list as each called/next()""" 
g_Result = cycle(l_Periods) 
for value in g_Result: 
    yield value 

    # Main Code 
go_52Oscillator = g_Oscillator([5, 2]) ## Primed Ocscillator 
go_34Oscillator = g_Oscillator([3, 4]) ## Primed Ocscillator 
go_ABCOscillator = g_Oscillator(["A", "B", "C"]) ## Primed Ocscillator 
for i in xrange(5): 
    print(go_34Oscillator.next()) 
print() 

for i in xrange(5): 
    print(go_52Oscillator.next()) 
print() 

for i in xrange(5): 
    print(go_ABCOscillator.next())