How do I use itertools.groupby()?

前端 未结 13 1733
失恋的感觉
失恋的感觉 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:42

    A neato trick with groupby is to run length encoding in one line:

    [(c,len(list(cgen))) for c,cgen in groupby(some_string)]
    

    will give you a list of 2-tuples where the first element is the char and the 2nd is the number of repetitions.

    Edit: Note that this is what separates itertools.groupby from the SQL GROUP BY semantics: itertools doesn't (and in general can't) sort the iterator in advance, so groups with the same "key" aren't merged.

    0 讨论(0)
提交回复
热议问题