0
a=[3.0,2.5,1.0,'1/3','4/5']

I would like to sort this array, i tried converting the strings to another array i.e,

a[3]=['1','3']

then converting them to float and then perform the division. the problem is, it becomes more complicated when i sort them using a.sort, I don't know how to bring them back to their string form I need to know how to this without importing the fraction module

Help please.

1 Answer 1

3

You don't need to convert it back. Use key parameter (a function) of sorted, list.sort. The return value of the key function will be used for comparison.

>>> def key(n):
...     if isinstance(n, str):
...         a, b = map(float, n.split('/'))
...         n = a / b
...     return n
... 
>>> a = [3.0,2.5,1.0,'1/3','4/5']
>>> sorted(a, key=key)
['1/3', '4/5', 1.0, 2.5, 3.0]
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.