Skip to main content
 首页 » 编程设计

python之如何根据 python 中的浮点值对列表中的元组字符串部分进行排序

2025年05月04日29hnrainll

我有一个元组列表,带有 Str 和 float

list =  
[('Trading_State_NZ <= 0.00', 0.0234), 
 ('Product_Type_A <= 0.00', 0.045643), 
 ('Permanent_Resident_Y <= 1.00', 0.0214), 
 ('Applicant_Type_B <= 1.00', 0.0236), 
 ('Valuation_Acceptable_Y <= 1.00', 0.0866), 
 ('Product_Type_6 <= 0.00', 0.0172), 
 ('Trading_State_NT <= 0.00', 0.0553), 
 ('Trading_State_TAS <= 0.00', 0.0251), 
 ('Property_Acceptable_Y <= 1.00', 0.01588), 
 ('Applicant_Type1_at1_miss <= 1.00', 0.0158758), 
 ('Product_Type_I <= 0.00', 0.01571), 
 ('Employer_Name <= 1.00', 0.0552), 
 ('Business_Name <= 0.00', 0.02557), 
 ('Product_Type_E <= 0.00', 0.02457), 
 ('Product_Type_CTP <= 0.00', 0.02457), 
 ('Trading_Postcode <= 1.00', 0.024572), 
 ('Trading_State_ts_miss <= 1.00', 0.0785), 
 ('Variation_2014 <= 0.00', 0.0694), 
 ('Product_Type_C <= 0.00', 0.017145), 
 ('Phone_Number <= 0.00', 0.0789678)] 

字符串部分前后两段 <= symbol, "Name <= value", 我希望将 0.00 和 1.00 值分开,然后根据浮点值降序排序

list.sort() 

list.sort() 基于字符串排序,我需要根据值拆分 str 并排序?

请您参考如下方法:

一种方法:

type0 = [] 
type1 = [] 
for tup in mytups: 
    if '<= 0' in tup[0]: 
        type0.append(tup) 
    else: 
        type1.append(tup) 
 
type0.sort(key=lambda x: x[1], reverse=True) 
type1.sort(key=lambda x: x[1], reverse=True) 
 
final_list = type0 + type1 

或者使用多级排序(无耻地建立在@Selcuk 的回答之上):

mytups.sort(key=lambda x: (float(x[0].split("<=")[1]), -x[1]))