How do I use itertools.groupby()?

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

    The example on the Python docs is quite straightforward:

    groups = []
    uniquekeys = []
    for k, g in groupby(data, keyfunc):
        groups.append(list(g))      # Store group iterator as a list
        uniquekeys.append(k)
    

    So in your case, data is a list of nodes, keyfunc is where the logic of your criteria function goes and then groupby() groups the data.

    You must be careful to sort the data by the criteria before you call groupby or it won't work. groupby method actually just iterates through a list and whenever the key changes it creates a new group.

提交回复
热议问题