0

I am trying to figure out how to sort a list based on a certain part of each string. How do I write the key?

myKey(e)
  return e[-5,-2]

print(sorted(["A: (" + str(round(7.24856, 2)) + ")", "B: (" + str(round(5.8333, 2)) + ")"], key = myKey))

I want the output to look like this: ['B: (5.83)', 'A: (7.25)']

In my full code, there are more than two strings in the list, so I cannot just sort them reversed alphabetically.

Thank you

3
  • What have you tried and call you please show all of the releveant code? Commented Apr 14, 2019 at 0:35
  • Can you clarify what you're doing exactly? Are you starting with numbers, and want to use them to produce sorted strings? Or are you starting with the numbers already in string form, and you need to sort them numerically anyway? Are there any limits on the numeric values (for instance, are they all less than 10)? It's not easy to tell from your example how complicated the parsing task might be. Commented Apr 14, 2019 at 0:39
  • please specify your input? Commented Apr 14, 2019 at 0:40

2 Answers 2

1

Your syntax for function myKey is wrong. Other than that, you have to slice out the number in the string with the correct index (from index of char '(' + 1 to the character before the last) and convert them to floating point number value so that the sorted function can work properly.

def myKey(e):
  return float(e[e.index('(')+1:-1])
print(sorted(["A: (" + str(round(7.24856, 2)) + ")", "B: (" + str(round(5.8333, 2)) + ")"], key = myKey))
Sign up to request clarification or add additional context in comments.

Comments

1

You can use tuples sorted() to sort your data alongside with some list and string expressions to get the desired output:

input_list = ['A:(100.27)', 'B:(2.36)', 'C:(75.96)', 'D:(55.78)']
tuples_list = [(e.split(':(')[0], float(e.split(':(')[1][:-1])) for e in input_list]
sorted_tuples = sorted(tuples_list, key=lambda x: x[1])
result = [x[0] +':('+ str(x[1]) +')' for x in sorted_tuples]

print(input_list)
print(tuples_list)
print(sorted_tuples)
print(result)

Output:

['A:(100.27)', 'B:(2.36)', 'C:(75.96)', 'D:(55.78)']
[('A', 100.27), ('B', 2.36), ('C', 75.96), ('D', 55.78)]
[('B', 2.36), ('D', 55.78), ('C', 75.96), ('A', 100.27)]
['B:(2.36)', 'D:(55.78)', 'C:(75.96)', 'A:(100.27)']

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.