One-step initialization of defaultdict that appends to list?

后端 未结 5 790
情话喂你
情话喂你 2021-02-19 01:09

It would be convenient if a defaultdict could be initialized along the following lines

d = defaultdict(list, ((\'a\', 1), (\'b\', 2), (\'c\', 3), (         


        
5条回答
  •  忘掉有多难
    2021-02-19 01:40

    Sorting and itertools.groupby go a long way:

    >>> L = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('a', 2), ('b', 3)]
    >>> L.sort(key=lambda t:t[0])
    >>> d = defaultdict(list, [(tup[0], [t[1] for t in tup[1]]) for tup in itertools.groupby(L, key=lambda t: t[0])])
    >>> d
    defaultdict(, {'a': [1, 2], 'c': [3], 'b': [2, 3], 'd': [4]})
    

    To make this more of a one-liner:

    L = [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('a', 2), ('b', 3)]
    d = defaultdict(list, [(tup[0], [t[1] for t in tup[1]]) for tup in itertools.groupby(sorted(L, key=operator.itemgetter(0)), key=lambda t: t[0])])
    

    Hope this helps

提交回复
热议问题