Python: Checking to which bin a value belongs

前端 未结 3 1121
盖世英雄少女心
盖世英雄少女心 2020-12-03 14:17

I have a list of values and a list of bin edges. Now I need to check for all values to what bin they belong to. Is there a more pythonic way than iterating over the values a

3条回答
  •  眼角桃花
    2020-12-03 15:22

    Maybe this will help get you on the right track:

    >>> import itertools
    >>> my_list = [3,2,56,4,32,4,7,88,4,3,4]
    >>> for k, g in itertools.groupby(sorted(my_list), lambda x: x // 20 * 20):
    ...     print k, list(g)
    ... 
    0 [2, 3, 3, 4, 4, 4, 4, 7]
    20 [32]
    40 [56]
    80 [88]
    

提交回复
热议问题