2

I want to sort list of countries based on continents, but want to keep 'Rest of Asia' and 'Rest of America' at the end. How can we modify the sort function

A = ['China', 'India', 'Brazil', 'Canada', 'Rest of Asia', 'Rest of America', 'USA', 'UAE', 'Sri Lanka']
sorted(A)

I want to have the result where Rest of America and Rest of Asia should come in the end

like: ['China', 'India', 'Brazil', 'Canada', 'USA', 'UAE', 'Sri Lanka', 'Rest of Asia','Rest of America']

Alec
  • 8,529
  • 8
  • 37
  • 63
Abdullah
  • 23
  • 2

2 Answers2

2

Remove the elements, sort the list, then re-append them:

A = sorted([x for x in A if "Rest" not in x]).append([x for x in A if "Rest" in x])
Alec
  • 8,529
  • 8
  • 37
  • 63
2

If all you want is the results starting with Rest at the end, you can use a custom sorter:

A = ['China', 'India', 'Brazil', 'Canada', 'Rest of Asia', 'Rest of America', 'USA', 'UAE', 'Sri Lanka']

def mySort(a):
    if a.startswith('Rest'):
        return 1
    return 0

A.sort(key=mySort)

Out[1]:
['China',
 'India',
 'Brazil',
 'Canada',
 'USA',
 'UAE',
 'Sri Lanka',
 'Rest of Asia',
 'Rest of America']

Or a simpler version with the anonymous call:

A.sort(key=lambda x: x.startswith('Rest'))
realr
  • 3,652
  • 6
  • 23
  • 34