使用 toolz Python 在 Pipe 中使用带有初始值的 reduce

Using reduce with initial value in a Pipe with toolz Python

我希望将 reduce 操作作为管道的一部分来执行,以根据键对 dict 项目进行排序。 例如

from toolz import pipe

items = [{"id":1, "val":1}, {"id":2, "val":2}, {"id":2, "val":3}]
res = pipe(items, reduce(combine_items), other_ops...)
# res = {1: [{'id': 1, 'val': 1}], 2: [{'id': 2, 'val': 2}, {'id': 2, 'val': 3}]}

def combine_items(record_list, item):
    record_list.setdefault(item.get("id"), []).append(item)
    return record_list

我已经设法使用 lambda 做到了这一点,即

res = pipe(items, lambda x: reduce(combine_items, x, {}), other_ops...)

我的问题是是否有另一种方法可以做到这一点而不必在管道中使用 lambda?

我遇到的主要问题是我的列表追加需要一个默认值才能在 reduce 中正常工作,我不确定是否有其他方法可以在管道中正确填充它。

您可以使用 toolz 中的 groupby() 而不是滚动您自己的 combine_items,它完全符合您在此处尝试执行的操作:

from toolz import groupby

res = groupby('id', items)

如果您想将其用作管道的一部分,则可以使用 functools.partial() 传递 groupby() 一个关键参数:

from toolz import groupby, pipe
from functools import partial

res = pipe(items, partial(groupby, 'id'), other_ops...)