我开始学习如何以函数式方式使用 python,但我遇到了一个我无法解决的问题。
我有以下代码(取自 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))
...
我总是从空列表开始,使用 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))
有人可以解释一下在这种情况下如何正确使用迭代器吗?
请您参考如下方法:
在功能上它看起来像这样:
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_url 是 pure function接受来自外部的一切。
并且您正在生成 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']
