itertools.groupby() not grouping correctly

后端 未结 3 1330
北恋
北恋 2020-11-28 13:53

I have this data:

self.data = [(1, 1, 5.0),
             (1, 2, 3.0),
             (1, 3, 4.0),
             (2, 1, 4.0),
             (2, 2, 2.0)]
         


        
3条回答
  •  旧时难觅i
    2020-11-28 14:20

    itertools.groupby collects together contiguous items with the same key. If you want all items with the same key, you have to sort self.data first.

    for mid, group in itertools.groupby(
        sorted(self.data,key=operator.itemgetter(1)), key=operator.itemgetter(1)):
    

提交回复
热议问题