One-step initialization of defaultdict that appends to list?

后端 未结 5 774
情话喂你
情话喂你 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:39

    I think most of this is a lot of smoke and mirrors to avoid a simple for loop:

    di={}
    for k,v in [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('a', 2),('b', 3)]:
        di.setdefault(k,[]).append(v)
    # di={'a': [1, 2], 'c': [3], 'b': [2, 3], 'd': [4]}
    

    If your goal is one line and you want abusive syntax that I cannot at all endorse or support you can use a side effect comprehension:

    >>> li=[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('a', 2),('b', 3)]
    >>> di={};{di.setdefault(k[0],[]).append(k[1]) for k in li}
    set([None])
    >>> di
    {'a': [1, 2], 'c': [3], 'b': [2, 3], 'd': [4]}
    

    If you really want to go overboard into the unreadable:

    >>> {k1:[e for _,e in v1] for k1,v1 in {k:filter(lambda x: x[0]==k,li) for k,v in li}.items()}
    {'a': [1, 2], 'c': [3], 'b': [2, 3], 'd': [4]}
    

    You don't want to do that. Use the for loop Luke!

提交回复
热议问题