How can I group equivalent items together in a Python list?

后端 未结 1 632
盖世英雄少女心
盖世英雄少女心 2020-12-06 12:09

I have a list like

x = [2, 2, 1, 1, 1, 1, 1, 1]

I would like to put the repeated numbers together like

[[2,2],[1,1,1,1,1,         


        
相关标签:
1条回答
  • 2020-12-06 12:51
    [list(g) for k, g in itertools.groupby(iterable)]
    

    This is exactly what itertools.groupby is for.

    If you want nonconsecutive numbers grouped, like in the comment by @Michal,

    [list(g) for k, g in itertools.groupby(sorted(iterable))]
    
    0 讨论(0)
提交回复
热议问题