【问题标题】:How to apply n-times a function with map如何使用 map 应用 n 次函数
【发布时间】:2015-12-12 18:27:39
【问题描述】:

我开始学习如何以函数式方式使用 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))

有人可以解释一下在这种情况下如何正确使用迭代器吗?

【问题讨论】:

    标签: python python-2.7 dictionary lambda functional-programming


    【解决方案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_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']
    

    【讨论】:

    • 谢谢,它工作得很好。仅供将来参考:您对按照我尝试的方式执行此操作有什么建议吗?我的意思是,如何用地图重复?
    • 我不认为你可以通过"xyz"上的单个地图轻松做到这一点
    【解决方案2】:

    前缀和后缀有损 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)]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-23
      • 2022-01-09
      • 2019-03-28
      • 2017-04-30
      • 2020-08-25
      • 2018-05-02
      • 1970-01-01
      相关资源
      最近更新 更多