0

I'm trying to come up with a specific order key in Python to sort my list of string numbers with specific criteria. The list elements all look like this:

["5,4287", "2,86", "4,92", "6,12", "6,11"]

and so on.

I want the elements of this list to be ordered in a specific order of criteria:

  • First order them by the prefix (the number before ',')
  • Then order them by the suffix

The resulting list should look like this:

["2,86", "4,92", "5,4287", "6,11", "6,12"]

I don't know how I can sort by multiple criteria in python or if this is even possible.

1
  • you can convert them float and than sort them. Commented Jul 23, 2020 at 10:09

1 Answer 1

1

Using str.split on comma and convert to int

Ex:

data =  ["5,4287", "2,86", "4,92", "6,12", "6,11"]
data.sort(key=lambda x: tuple(map(int, x.split(","))))
print(data)

Output:

['2,86', '4,92', '5,4287', '6,11', '6,12']
Sign up to request clarification or add additional context in comments.

Comments

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.