How do I use itertools.groupby()?

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

    You can write own groupby function:

               def groupby(data):
                    kv = {}
                    for k,v in data:
                        if k not in kv:
                             kv[k]=[v]
                        else:
                            kv[k].append(v)
               return kv
    
         Run on ipython:
           In [10]: data = [('a', 1), ('b',2),('a',2)]
    
            In [11]: groupby(data)
            Out[11]: {'a': [1, 2], 'b': [2]}
    

提交回复
热议问题