gpt4 book ai didi

python - Python 中类似 Javascript 的数组方法链接?

转载 作者:太空宇宙 更新时间:2023-11-03 13:26:55 24 4
gpt4 key购买 nike

我是从 javascript 背景进入 python 的。在 JS 中,我们可以进行数组方法链接,这很棒(尤其是箭头函数):

someArray
.filter(x => x.count > 10)
.sort((a, b) => a.count - b.count)
.map(x => x.name)

在 python 中是否可以使用数组方法链接之类的东西,如果不能,那到底为什么不能呢?

最佳答案

在 Python 中,你会这样做:

from operator import attrgetter
map(lambda x: x.name,
sorted(filter(lambda x: x.count > 10, someArray),
key=attrgetter("count"))

语法略有不同,但基本上应该是一样的。这是否回答了您的问题?

编辑

如果你真的想要更“链状”的语法,你可以看看toolz .来自他们的 docs :

>>> from toolz.curried import pipe, map, filter, get
>>> pipe(accounts, filter(lambda acc: acc[2] > 150),
... map(get([1, 2])),
... list)

编辑2

感谢@mpium 建议 PyFunctional,它似乎有一个更酷的语法:

from functional import seq

seq(1, 2, 3, 4)\
.map(lambda x: x * 2)\
.filter(lambda x: x > 4)\
.reduce(lambda x, y: x + y)
# 14

关于python - Python 中类似 Javascript 的数组方法链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53710406/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com