Divide a list into multiple lists based on a bin size

前端 未结 6 533
悲哀的现实
悲哀的现实 2021-01-18 03:02

I have a list containing more than 100,000 values in it.

I need to divide the list into multiple smaller lists based on a specific bin width say 0.1. Can anyone hel

6条回答
  •  囚心锁ツ
    2021-01-18 03:34

    This works:

    l=[-0.234, -0.04325, -0.43134, -0.315, -0.6322, -0.245,
    -0.5325, -0.6341, -0.5214, -0.531, -0.124, -0.0252]
    
    d={}
    for k,v in zip([int(i*10) for i in l],l):
       d.setdefault(k,[]).append(v)
    
    LoL=[d[e] for e in sorted(d.keys(), reverse=True)]
    
    for i,l in enumerate(LoL,1):
        print('list',i,l)    
    

    Prints:

    list 1 [-0.04325, -0.0252]
    list 2 [-0.124]
    list 3 [-0.234, -0.245]
    list 4 [-0.315]
    list 5 [-0.43134]
    list 6 [-0.5325, -0.5214, -0.531]
    list 7 [-0.6322, -0.6341]
    

    How it works:

    1: The list
    >>> l=[-0.234, -0.04325, -0.43134, -0.315, -0.6322, -0.245,
    ... -0.5325, -0.6341, -0.5214, -0.531, -0.124, -0.0252]
    
    2: Produce the keys:
    >>> [int(i*10) for i in l]
    [-2, 0, -4, -3, -6, -2, -5, -6, -5, -5, -1, 0]
    
    3: Produce tuples to put in the dict:
    >>> zip([int(i*10) for i in l],l)
    [(-2, -0.234), (0, -0.04325), (-4, -0.43134), (-3, -0.315), (-6, -0.6322), 
     (-2, -0.245), (-5, -0.5325), (-6, -0.6341), (-5, -0.5214), (-5, -0.531), 
     (-1, -0.124), (0, -0.0252)]
    
    4: unpack the tuples into k,v and loop over the list
    >>>for k,v in zip([int(i*10) for i in l],l):
    
    5: add k key to a dict (if not there) and append the float value to a list associated 
       with that key:
        d.setdefault(k,[]).append(v)
    

    I suggest a Python tutorial on these statements.

提交回复
热议问题