python - 链接 map 和过滤器的 Python 方式是什么?

标签 python

我目前正在学习 Python(来自 JavaScript 和 Ruby 等其他语言)。我非常习惯于链接一堆转换/过滤器​​,但我很确定这不是在 Python 中这样做的正确方法:filter 在可枚举之前需要一个 lambda,所以写一个长/多行函数看起来很奇怪,将它们链接起来意味着将它们以相反的顺序排列,这是不可读的。

在这个 JavaScript 函数中编写 map 和过滤器的“Python 方式”是什么?

let is_in_stock = function() /* ... */
let as_item = function() /* ... */

let low_weight_items = shop.inventory
    .map(as_item)
    .filter(is_in_stock)
    .filter(item => item.weight < 1000)
    .map(item => {
        if (item.type == "cake") {
            let catalog_item = retrieve_catalog_item(item.id);

            return {
                id: item.id,
                weight: item.weight,
                barcode: catalog_item.barcode
            };
        } else {
            return default_transformer(item);
        }
    });

我知道我可能会对第一张 map 和接下来的两个过滤器使用列表推导,但我不确定如何制作最后一张 map 以及如何将所有内容放在一起。

谢谢!

最佳答案

如果您不介意使用包,这是使用 https://github.com/EntilZha/PyFunctional 的另一种方法。

from functional import seq

def as_item(x):
    # Implementation here
    return x

def is_in_stock(x):
    # Implementation
    return True

def transform(item):
    if item.type == "cake":
        catalog_item = retrieve_catalog_item(item.id);
        return {
            'id': item.id,
            'weight': item.weight,
            'barcode': catalog_item.barcode
        }
    else:
        return default_transformer(item)

low_weight_items = seq(inventory)\
    .map(as_item)\
    .filter(is_in_stock)\
    .filter(lambda item: item.weight < 1000)\
    .map(transform)

如前所述,python 允许您使用 lamdba 表达式,但它们不像 javascript 中的 clojures 那样灵活,因为它们不能有多个语句。另一个恼人的 python 事情是需要反斜杠。话虽如此,我认为以上内容最接近于您最初发布的内容。

免责声明:我是上述包的作者

关于python - 链接 map 和过滤器的 Python 方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24831476/

相关文章:

python - 将状态传递给函数与调用类实例上的方法

python - 安装多个python版本时,如何将模块添加到特定的python版本?

python - Python机器学习中只有标签为真时如何计算特征百分比?

python - 在每个第 n 个元素之后插入 Python 列表中的元素

python - 如何循环嵌套字典列表并带来 k :v pairs to 1st-level dictionary? JSON 数据

python - 在 Pytest 中使用 excel 参数化测试

python - Django - 将 ForeignKey 关系更改为 OneToOne

python - 在 osx for django 的 virtualenv 中安装 mysql

python - 如何删除json文件python中的元素

python - 不能在 Heroku 中使用 django-compress