代码之家  ›  专栏  ›  技术社区  ›  463035818_is_not_an_ai

如何通过pytholy生成给定对象列表的成员字典?

  •  0
  • 463035818_is_not_an_ai  · 技术社区  · 5 年前

    我有这个类的对象列表:

    class foo:
        def __init__(self,x,y):
            self.x = x
            self.y = y
        def __repr__(self):
            return "(" + str(self.x) + "," + str(self.y) + ")"
    

    现在我要创建一个字典,其中包含 x 列表(排序的、唯一的元素) y 价值观。我写了这个

    def get_xy_dict(lis):
        outp = {}
        for e in lis:
            if (e.x in outp): 
                outp[e.x].add(e.y)
            else:
                outp[e.x] = set([e.y])
        return outp
    

    像这样使用它,它可以按预期工作:

    x = [ foo(1,2), foo(1,3), foo(3,6), foo(1,3)]
    y = get_xy_dict(x)
    print(x)
    print(y)
    

    印刷品(见) here ):

    [(1,2), (1,3), (3,6), (1,3)]                                                                                                                                                                  
    {1: {2, 3}, 3: {6}}   
    

    但是,我觉得我的代码非常笨拙。此外,我更喜欢列表而不是集合。也许可以完全避免使用这些集合。同样,输出排序也是通过Conincidence进行的,如果我再加上一点,它会变得更加笨拙。

    怎样才能获得相同的输出(最好是列表而不是集合)?例如,如何生成包含所有值的字典 Y 那似乎是给的 X ?

    附言:不确定,如果这是属于代码审查,请告诉我。

    2 回复  |  直到 5 年前
        1
  •  1
  •   Patrick Haugh    5 年前

    您可以使用 sorted 功能。结合A defaultdict 您可以大大简化代码:

    from collections import defaultdict
    
    def get_xy_dict(lis):
        d = defaultdict(set)
        for e in lis:
            d[e.x].add(e.y)
        return {k: sorted(v) for k, v in d.items()}  # This creates a new dict, but you could also 
                                                     # change the values of d
    
    x = [ foo(1,2), foo(1,3), foo(3,6), foo(1,3)]
    y = get_xy_dict(x)
    print(x)  # [(1,2), (1,3), (3,6), (1,3)]
    print(y)  # {1: [2, 3], 3: [6]}
    
        2
  •  2
  •   Laurent LAPORTE    5 年前

    您首先需要按 X 属性,然后您可以对它们进行分组。

    一种方法是使用 itertools.groupby ,像这样:

    import itertools
    import operator
    
    
    sort_key = operator.attrgetter('x')
    y = {k: set(v.y for v in group)
         for k, group in itertools.groupby(sorted(x, key=sort_key), sort_key)}
    print(y)
    

    你得到:

    {1: {2, 3}, 3: {6}}