Group Python List Elements

后端 未结 4 1878
误落风尘
误落风尘 2021-01-29 10:49

I have a python list as follows:

my_list = 

 [[25, 1, 0.65],
 [25, 3, 0.63],
 [25, 2, 0.62],
 [50, 3, 0.65],
 [50, 2, 0.63], 
 [50, 1, 0.62]]

4条回答
  •  孤独总比滥情好
    2021-01-29 11:27

    You can sort your list with native python, but I find it easiest to get your required list using numpy. Since you were going to use pandas anyway, I consider this to be an acceptable solution:

    from operator import itemgetter
    import numpy as np
    # or just use pandas.np if you have that already imported
    
    my_list = [[25, 1, 0.65],
     [25, 3, 0.63],
     [25, 2, 0.62],
     [50, 3, 0.65],
     [50, 2, 0.63],
     [50, 1, 0.62]]
    
    sorted_list = sorted(my_list,key=itemgetter(1,0)) # sort by second and first column
    sliced_array = np.array(sorted_list)[:,-1].reshape(-1,2)
    final_list = sliced_array.tolist() # to get a list
    

    The main point is to use itemgetter to sort your list on two columns one after the other. The resulting sorted list contains the required elements in its third column, which I extract with numpy. It could be done with native python, but if you're already using numpy/pandas, this should be natural.

提交回复
热议问题