Converting a list of tuples into a dict

前端 未结 5 1196
走了就别回头了
走了就别回头了 2020-11-27 05:16

I have a list of tuples like this:

[
(\'a\', 1),
(\'a\', 2),
(\'a\', 3),
(\'b\', 1),
(\'b\', 2),
(\'c\', 1),
]

I want to iterate through th

5条回答
  •  长情又很酷
    2020-11-27 05:41

    A solution using groupby

        >>> from itertools import groupby
        >>> l = [('a',1), ('a', 2),('a', 3),('b', 1),('b', 2),('c', 1),]
        >>> [(label, [v for l,v in value]) for (label, value) in groupby(l, lambda x:x[0])]
        [('a', [1, 2, 3]), ('b', [1, 2]), ('c', [1])]
    

    groupby(l, lambda x:x[0]) gives you an iterator that contains ['a', [('a', 1), ...], c, [('c', 1)], ...]

提交回复
热议问题