2015-09-16 18 views
2

我開始學習如何以功能的方式使用python,並且遇到了我無法解決的問題。如何在地圖上應用n次函數

我有下面的代碼(帶部分來自this question),這不正是我想要的:

url = "www.testpage.com/" 
def gen_url(prefix, suffix, places=3): 
    pattern = "{}{{:0{}d}}{}".format(prefix, places, suffix) 
    for i in count(1): 
     yield pattern.format(i) 

list_of_urls = [] 
for c in "xyz": 
    g = gen_url(url+c,"&show=more") 
    for x in range(2): 
     list_of_urls.append(next(g)) 

它產生這樣的:

www.testpage.com/x001&show=more 
www.testpage.com/y001&show=more 
www.testpage.com/z001&show=more 
www.testpage.com/x002&show=more 
www.testpage.com/y002&show=more 
www.testpage.com/z002&show=more 

正如你所看到的,它在002停止因爲:

... 
    for x in range(2): 
     list_of_urls.append(next(g)) 
    ... 

所有的時間我一開始empy列表,u選擇一個for循環並填充它。我試圖用這種方式使用map並擺脫for循環:

urls = map(lambda x:next(gen_url(url+x,"&show=more")),"xyz") 

它的工作原理。但我只能達到001.假設我想達到002;我想類似下面的,但它不工作:

urls = imap((lambda x:next(gen_url(url+x,"&show=more")),"xyz"),2) 

而這也不起作用:

urls = map((lambda x:next(gen_url(url+x,"&show=more")),"xyz"),repeat(2)) 

有人能解釋我如何正確使用迭代器在這案件?

回答

1

在功能上它應該是這樣的:

def gen_url(prefix, suffix, id, places=3): 
    pattern = "{}{{:0{}d}}{}".format(prefix, places, suffix) 
    return pattern.format(id) 

url = "www.testpage.com/" 
a = [ gen_url(url + l, "&show=more", n) for l in "xyz" for n in range(1,4) ] 
print a 

所以,現在你gen_urlpure function從外部接受一切。

而且your're產生2個序列"xyz"[1, 2, 3]

上面的腳本產生的笛卡爾乘積(基本上全部排列):

['www.testpage.com/x001&show=more', 
'www.testpage.com/x002&show=more', 
'www.testpage.com/x003&show=more', 
'www.testpage.com/y001&show=more', 
'www.testpage.com/y002&show=more', 
'www.testpage.com/y003&show=more', 
'www.testpage.com/z001&show=more', 
'www.testpage.com/z002&show=more', 
'www.testpage.com/z003&show=more'] 
+0

謝謝,它完美的作品。僅供將來參考:您是否有任何建議以我嘗試的方式進行此操作?我的意思是,如何重複地圖? – Angelo

+0

我不認爲你可以輕鬆地通過''xyz「 – zerkms

1

前綴和後綴從簡單的邏輯在gen_url減損。 他們可以被拉出。

試試這個:

from itertools import count, islice 

def gen_url(places=3): 
    for i in count(1): 
     yield "{{:0{}d}}".format(places).format(i) 

url = "www.testpage.com/" 
list_of_urls = [url+c+x+"&show=more" for c in "xyz" for x in islice(gen_url(), 0, 2)] 
相關問題