Converting a list of tuples into a dict

前端 未结 5 1192
走了就别回头了
走了就别回头了 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:25

    Print list of tuples grouping by the first item

    This answer is based on the @gommen one.

    #!/usr/bin/env python
    
    from itertools import groupby
    from operator  import itemgetter
    
    L = [
    ('a', 1),
    ('a', 2),
    ('a', 3),
    ('b', 1),
    ('b', 2),
    ('c', 1),
    ]
    
    key = itemgetter(0)
    L.sort(key=key) #NOTE: use `L.sort()` if you'd like second items to be sorted too
    for k, group in groupby(L, key=key):
        print k, ' '.join(str(item[1]) for item in group)
    

    Output:

    a 1 2 3
    b 1 2
    c 1
    

提交回复
热议问题