【问题标题】:Pluck in Python在 Python 中采摘
【发布时间】:2013-05-23 17:23:31
【问题描述】:

我今天开始阅读 underscore.js,它是一个用于 javascript 的库,它添加了一些我习惯于在 Python 中使用的函数式编程好东西。一种很酷的速记方法是pluck

确实,在 Python 中,我经常需要提取一些特定的属性,并最终这样做:

users = [{
    "name" : "Bemmu",
    "uid" : "297200003"
},
{
    "name" : "Zuck",
    "uid" : "4"
}]
uids = map(lambda x:x["uid"], users)

如果下划线速记在 Python 中的某个地方,这是可能的:

uids = pluck(users, "uid")

添加当然是微不足道的,但在 Python 中是否已经存在?

【问题讨论】:

    标签: python functional-programming


    【解决方案1】:

    只需在任何使用uids 的函数中使用列表推导:

    而不是

    uids = map(operator.itemgetter("uid"), users)
    foo(uids)
    

    foo([x["uid"] for x in users])
    

    如果您只是希望 uids 进行迭代,则无需创建列表 - 而是使用生成器。 (将[] 替换为()。)


    例如:

    def print_all(it):
        """ Trivial function."""
        for i in it:
            print i
    
    print_all(x["uid"] for x in users)
    

    【讨论】:

    • 可以使用x.get('uid', None)None 是默认值)来避免在项目没有 uid 时引发异常。
    【解决方案2】:

    您可以从 funcy 模块 (https://github.com/Suor/funcy) 中选择 pluck 功能。

    在这种情况下,如果您的主机上提供了 funcy,则以下代码应该可以按预期工作:

    from funcy import pluck
    
    users = [{
        "name" : "Bemmu",
        "uid" : "297200003"
    },
    {
        "name" : "Zuck",
        "uid" : "4"
    }]
    
    uids = pluck("uid", users)
    

    注意参数的顺序与 underscore.js 使用的顺序不同

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-30
      • 2012-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多