Home > OS >  How to sort Python strings both alphabetically by prefix and numerically by suffix?
How to sort Python strings both alphabetically by prefix and numerically by suffix?

Time:11-03

I need to sort a list of strings, of the form:

["ccc_3.23", "b_0.00", "b_-1.10", "aa_-2.37", "aa_3.05", "aa_-2.11", "ccc_9.8"]

first by prefix, then by suffix, such that the sorted list is:

["aa_-2.37", "aa_-2.11", "aa_3.05", "b_-1.17", "b_0.00", "ccc_3.23", "ccc_9.8"]

The prefixes only contain standard english letters, and can be of any length. The suffixes, on the other hand, are always signed floats, with potentially varying numbers of digits. -1.3232, 0.0, and 7.98 are all valid suffixes.

The list needs to be sorted without altering any of its elements in the process. I've tried a number of different approaches from accross the web, but none seem to cover every edge case here. Unfortunately, the list is formatted as-is, and I cannot do anything about it.

Is there any way that I could go about doing this?

CodePudding user response:

You need to use key in sort

a = ["ccc_3.23", "b_0.00", "b_-1.10", "aa_-2.37", "aa_3.05", "aa_-2.11", "ccc_9.8"]
a.sort(key=lambda x: (x.split("_")[0], float(x.split("_")[1])))
a
# output : ['aa_-2.37', 'aa_-2.11', 'aa_3.05', 'b_-1.10', 'b_0.00', 'ccc_3.23', 'ccc_9.8']
  • Related