Python采摘

2024-05-13 21:00:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我今天开始阅读关于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中已经有了吗?


Tags: 工具方法函数nameuid编程文章js
2条回答

只要在任何函数中使用列表理解即可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)

funcy模块(https://github.com/Suor/funcy)中,您可以选择提取函数。

在这种情况下,如果在主机上可以使用funcy,则以下代码应按预期工作:

from funcy import pluck

users = [{
    "name" : "Bemmu",
    "uid" : "297200003"
},
{
    "name" : "Zuck",
    "uid" : "4"
}]

uids = pluck("uid", users)

注意参数的顺序不同于下划线.js使用的顺序

相关问题 更多 >