gpt4 book ai didi

Python 相当于 Scala groupby

转载 作者:行者123 更新时间:2023-12-01 04:28:13 25 4
gpt4 key购买 nike

我有一个对象列表,我想要一个函数,可以将该列表与对该列表中的项目进行操作的函数一起使用,并根据将该函数应用于该项目的结果生成一个带有键的字典,值是具有该键的项目列表。

示例:

def group_by(iterable: Iterable[A], f: Callable[A, B]) -> Dict[B, List[A]]:
???

lst = [(1,2), (3,4), (1,3)]
result = group_by(lst, lambda i: i[0])
result == {1: [(1,2), (1,3)],
3: [(3,4)]}

itertools.groupby 很接近,但我不想要求对我的输入进行排序。

最佳答案

这是使用 defaultdict 的方法:

from collections import defaultdict
def group_by(iterable, f):
results = defaultdict(list)
for x in iterable:
results[f(x)].append(x)
return results

关于Python 相当于 Scala groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32789591/

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