-1

I need to use the sorted() function in order to get from here:

test2 = [1,'2',3,'4',5,'A']

to here (create a new list which first has the sorted integers, and then has the sorted strings):

test2 = [1,3,5,'2','4','A']
Maiia S.
  • 313
  • 6
  • 12

3 Answers3

4
sorted(test2, key=lambda x: (isinstance(x, str), x))

This relies on the fact that False < True and that tuples are sorted lexicographically.

More details:

Tuples are often used to sort by more than one metric. Consider this:

key=lambda x: isinstance(x, str)

The key keyword argument to sorted tells it to sort values by the results of the given callable and not by the vaules themselves. This key will return False for integers and True for strings. Since False is equivalent to 0 and True to 1, False is considered smaller and all the integers will be sorted first in the list.

This is only half of what we want because the integers and strings are not sorted among themselves. This is were tuples come in. The above key function:

key=lambda x: (isinstance(x, str), x)

Returns a tuple for each element. Tuples are first sorted by their first element. If two tuples have an equivalent first element, their second elements are compared and so on. This is called lexigoraphic sorting. Let's say we have this list:

this = ["a", 5, "b", 3]

The key function would return, in order:

(True, "a"), (False, 5), (True, "b"), (False, 3)

The tuples will be sorted first by their first element, the booleans:

(False, 5), (False, 3), (True, "a"), (True, "b")

Now, we have two pairs of tuples which are equal by their first element. Each pair will be sorted internally by their second element:

(False, 3), (False, 5), (True, "a"), (True, "b")

The final result is not the tuples themselves but the corresponding input to the key function for each tuple:

[3, 5, "a", "b"]

In reality, the algorithm doesn't need to sort "twice" but it's conceptually the same.

roeen30
  • 759
  • 3
  • 13
0

Try this:

test2 = sorted([i for i in test2 if isinstance(i, int)]) + \
        sorted([i for i in test2 if isinstance(i, str)])
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
0

Filter the numbers and strings separately and then concatenate them.

num = list(filter(lambda x: type(x)==int, test2)) 
string = list(filter(lambda x: type(x)==str, test2))
sorted(num)+sorted(string) 
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
PIG
  • 599
  • 3
  • 13