Reputation: 1616
I have a list of tuples, with a 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)]
The string part has two sections before and after <= symbol, "Name <= value", I am looking to separate 0.00 and 1.00 values then sort in descending order based on the float value
list.sort()
list.sort() sorting based on string, I need the split the str based on value and sort?
Upvotes: 1
Views: 179
Reputation: 1989
One way to do it:
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
Or using a multi level sort (shamelessly built upon @Selcuk answer):
mytups.sort(key=lambda x: (float(x[0].split("<=")[1]), -x[1]))
Upvotes: 3
Reputation: 59228
You can use the following:
my_list.sort(key=lambda x: -float(x[0].split("<=")[1]))
The lambda
function simply splits the 0
th element of a tuple using "<="
as a separator then converts the second part ([1]
) of the split to a float
. The .sort()
method then uses this lambda
function as the key.
Upvotes: 2