1

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?

0

2 Answers 2

3

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]))
Sign up to request clarification or add additional context in comments.

Comments

2

You can use the following:

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

The lambda function simply splits the 0th 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.

1 Comment

@DSC From the question text: [...] sorting based on string, I need the split the str based on value and sort. They are talking about the float value after <=.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.