How do I use itertools.groupby()?

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

    WARNING:

    The syntax list(groupby(...)) won't work the way that you intend. It seems to destroy the internal iterator objects, so using

    for x in list(groupby(range(10))):
        print(list(x[1]))
    

    will produce:

    []
    []
    []
    []
    []
    []
    []
    []
    []
    [9]
    

    Instead, of list(groupby(...)), try [(k, list(g)) for k,g in groupby(...)], or if you use that syntax often,

    def groupbylist(*args, **kwargs):
        return [(k, list(g)) for k, g in groupby(*args, **kwargs)]
    

    and get access to the groupby functionality while avoiding those pesky (for small data) iterators all together.

提交回复
热议问题