How can I use python itertools.groupby() to group a list of strings by their first character?

前端 未结 4 1382
迷失自我
迷失自我 2020-12-13 22:30

I have a list of strings similar to this list:

tags = (\'apples\', \'apricots\', \'oranges\', \'pears\', \'peaches\')

How should I go about

4条回答
  •  失恋的感觉
    2020-12-13 23:08

    >>> for i, j in itertools.groupby(tags, key=lambda x: x[0]):
        print(i, list(j))
    
    
    a ['apples', 'apricots']
    o ['oranges']
    p ['pears', 'peaches']
    

提交回复
热议问题