首页 > 解决方案 > 在python中根据另一个子列表中的相应权重对子列表进行排序

问题描述

我有两个嵌套列表list1list2. list1表示我需要排序的值的子列表,根据list2代表权重的第二个子列表list1

list1 = [[0.002, 0.001, 0.002, 0.1, 0.001, 0.2, 0.03, 0.04, 0.002, 0.03, 0.004, 0.0004, 0.005, 0.05],
         [0.007, 0.0001, 0.0002, 0.0001, 0.001, 0.02, 0.0003, 0.007, 0.007, 0.008, 0.0006, 0.0004, 0.005, 0.05],
         [0.0009, 0.000, 0.0002, 0.9, 0.091, 0.2, 0.03, 0.04, 0.002, 0.03, 0.004, 0.0004, 0.005, 0.0009],
         [0.002, 0.001, 0.002, 0.1, 0.001, 0.2, 0.03, 0.04, 0.002, 0.03, 0.004, 0.0004, 0.005, 0.055]]
   


  list2 =[[0.06165411, 0.04111233, 0.06165411, 0.049487340000000005, 0.04111233, 0.020541780000000003, 0.04111233, 0.020541780000000003, 0.06165411, 0.04111233, 0.020541780000000003, 0.0, 0.0, 0.049487340000000005], 
          [0.29708409, 0.19810227000000002, 0.049487340000000005, 0.19810227000000002, 0.020541780000000003, 0.09898182000000001, 0.09898182000000001, 0.29708409, 0.29708409, 0.09898182000000001, 0.09898182000000001, 0.0, 0.0, 0.049487340000000005], 
          [0.19810227000000002, 0.09898182000000001, 0.049487340000000005, 0.09898182000000001, 0.09898182000000001, 0.020541780000000003, 0.04111233, 0.020541780000000003, 0.020541780000000003, 0.04111233, 0.020541780000000003, 0.0, 0.0, 0.19810227000000002], 
          [0.06165411, 0.04111233, 0.06165411, 0.049487340000000005, 0.04111233, 0.020541780000000003, 0.04111233, 0.020541780000000003, 0.06165411, 0.04111233, 0.020541780000000003, 0.0, 0.0, 0.09898182000000001]]

我想list1根据 中的相应排序子列表对每个子列表进行排序list2。我写了以下代码:

def sort_list(list1, list2):
    z = [x for _, x in sorted(zip(list2, list1))]
    return(z)

sort_fea = []
for i in range(len(list1)):
    c1 = list1[i]
    c2 = list2[i]
    sort_fea.append(sort_list(c1, c2))
print('The sorted_list1 =',sort_fea)

我得到以下正确结果:

sorted_list1 =[[0.0004, 0.005, 0.004, 0.04, 0.2, 0.001, 0.001, 0.03, 0.03, 0.05, 0.1, 0.002, 0.002, 0.002],
               [0.0004, 0.005, 0.001, 0.0002, 0.05, 0.0003, 0.0006, 0.008, 0.02, 0.0001, 0.0001, 0.007, 0.007, 0.007],
               [0.0004, 0.005, 0.002, 0.004, 0.04, 0.2, 0.03, 0.03, 0.0002, 0.0, 0.091, 0.9, 0.0009, 0.0009],
               [0.0004, 0.005, 0.004, 0.04, 0.2, 0.001, 0.001, 0.03, 0.03, 0.1, 0.002, 0.002, 0.002, 0.055]]

有没有更快的方法使用numpy或任何其他方法?

标签: pythonnumpynested-lists

解决方案


sort_fea = []
for i in range(len(list1)):
    result = [x for _, x in sorted(zip(list2[i], list1[i]))]
    sort_fea.append(result)
print(sort_fea)

输出:

[[0.0004, 0.005, 0.004, 0.04, 0.2, 0.001, 0.001, 0.03, 0.03, 0.05, 0.1, 0.002, 0.002, 0.002],
 [0.0004, 0.005, 0.001, 0.0002, 0.05, 0.0003, 0.0006, 0.008, 0.02, 0.0001, 0.0001, 0.007, 0.007, 0.007],
 [0.0004, 0.005, 0.002, 0.004, 0.04, 0.2, 0.03, 0.03, 0.0002, 0.0, 0.091, 0.9, 0.0009, 0.0009],
 [0.0004, 0.005, 0.004, 0.04, 0.2, 0.001, 0.001, 0.03, 0.03, 0.1, 0.002, 0.002, 0.002, 0.055]]

据我所知,这将加速您的代码。


推荐阅读