How do I use itertools.groupby()?

前端 未结 13 1754
失恋的感觉
失恋的感觉 2020-11-22 02:14

I haven\'t been able to find an understandable explanation of how to actually use Python\'s itertools.groupby() function. What I\'m trying to do is this:

<
13条回答
  •  故里飘歌
    2020-11-22 02:34

    One useful example that I came across may be helpful:

    from itertools import groupby
    
    #user input
    
    myinput = input()
    
    #creating empty list to store output
    
    myoutput = []
    
    for k,g in groupby(myinput):
    
        myoutput.append((len(list(g)),int(k)))
    
    print(*myoutput)
    

    Sample input: 14445221

    Sample output: (1,1) (3,4) (1,5) (2,2) (1,1)

提交回复
热议问题