代码之家  ›  专栏  ›  技术社区  ›  Carbon

有更好的python等价物吗?

  •  0
  • Carbon  · 技术社区  · 7 年前

    Haskell有一个很棒的函数,mapKeysWith。在地图的关键点上,它应用一些变换,将数据对象与给定函数结合起来,以防现在发生冲突。我创建了下面的示例代码,非常详细。还有更像蟒蛇的方式吗?

    def mapKeysWith(combineF,op,mp):
        ret = {}
        for it in mp:
            if op(it) in ret:
                ret[op(it)] = combineF(ret[op(it)],mp[it])
            else:
                ret[op(it)] = mp[it]
        return ret
    
    z = {1:2,3:4,10:11}
    mapKeysWith(lambda x,y: x+y,lambda x: math.floor(x/10),z)
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Dani Mesejo    7 年前

    以下是两种可能的替代方案:

    import math
    from functools import reduce
    from collections import defaultdict
    
    
    def map_keys_with(combine_f, op, mp):
        ret = {}
        for it in mp:
    
            if op(it) in ret:
                ret[op(it)] = combine_f(ret[op(it)], mp[it])
            else:
                ret[op(it)] = mp[it]
        return ret
    
    
    def map_keys_with_setdefault(combine_f, op, mp):
        ret = {}
        for key, value in mp.items():
            ret.setdefault(op(key), []).append(value)
    
        return {key: reduce(combine_f, values) for key, values in ret.items()}
    
    
    def map_keys_with_defaultdict(combine_f, op, mp):
        ret = defaultdict(list)
        for key, value in mp.items():
            ret[op(key)].append(value)
        return {key: reduce(combine_f, values) for key, values in ret.items()}
    
    
    z = {1: 2, 3: 4, 10: 11}
    print(map_keys_with(lambda x, y: x + y, lambda x: math.floor(x / 10), z))
    print(map_keys_with_setdefault(lambda x, y: x + y, lambda x: math.floor(x / 10), z))
    print(map_keys_with_defaultdict(lambda x, y: x + y, lambda x: math.floor(x / 10), z))
    

    输出

    {0: 6, 1: 11}
    {0: 6, 1: 11}
    {0: 6, 1: 11}