python groupby behaviour?

后端 未结 3 741
星月不相逢
星月不相逢 2020-11-27 08:02
>>from itertools import groupby
>>keyfunc = lambda x : x > 500
>>obj = dict(groupby(range(1000), keyfunc))
>>list(obj[True])
         


        
3条回答
  •  一个人的身影
    2020-11-27 08:39

    The thing you are missing is, that the groupby-function iterates over your given range(1000), thus returning 1000 values. You are only saving the last one, in your case 999. What you have to do is, is to iterate over the return values and save them to your dictionary:

    dictionary = {}
    keyfunc = lambda x : x > 500
    for k, g in groupby(range(1000), keyfunc):
        dictionary[k] = list(g)
    

    So the you would get the expected output:

    {False: [0, 1, 2, ...], True: [501, 502, 503, ...]}
    

    For more information, see the Python docs about itertools groupby.

提交回复
热议问题