python: group elements of a tuple having the same first element

前端 未结 4 700
予麋鹿
予麋鹿 2021-01-19 01:27

i have a tuple like this

[
(379146591, \'it\', 55, 1, 1, \'NON ENTRARE\', \'NonEntrate\', 55, 1), 
(4746004, \'it\', 28, 2, 2, \'NON ENTRARE\', \'NonEntrate\         


        
4条回答
  •  不知归路
    2021-01-19 01:41

    u can use collection.defaultdict:

    data = [
        (379146591, 'it', 55, 1, 1, 'NON ENTRARE', 'NonEntrate', 55, 1), 
        (4746004, 'it', 28, 2, 2, 'NON ENTRARE', 'NonEntrate', 26, 2), 
        (4746004, 'it', 28, 2, 2, 'TheBestTroll Group', 'TheBestTrollGroup', 2, 3)
        ]
    from collections import defaultdict
    a = defaultdict(list)
    a = defaultdict(list)
    
    
    from collections import defaultdict
    a = defaultdict(list)
    
    for d in data:
        a[d[0]].append(d[1:])
    
    for k,v in a.items():
        a[k] = tuple(a[k])
    
    print(dict(a))
    

提交回复
热议问题