List sorting in python combine with string

Viewed 23

I have a string that goes like this string = "CCB" and a list

list = ['C','C','B','CC']

How do i sort them by their appearance order in the string (high priority) and their length(lower priority). After sorted the list should be like this

list = ['C' , 'C ', 'CC' , 'B']

I'm having some problem with this. does anyone have a python function or how to implement this problem?

1 Answers

One method is to create tuples of the indices and length before sorting, then reducing to the original input after. Below is one such example of doing this. Note that if the index is not found, we assume that it should come at the end and then just be sorted by length.

def sortby_index_length(input, items):
  def index_or_large(haystack, needle):
    try:
      return haystack.index(needle)
    except ValueError:
      return len(haystack)

  indexes = list(map(lambda x: (x, index_or_large(input, x)), items))
  indexes.sort(key=lambda xy: (xy[1], len(xy[0])))
  return list(map(lambda x: x[0], indexes))

print(sortby_index_length("CCB", ['C','C','B','CC']))

Which gives the expected output of ['C', 'C', 'CC', 'B']. This also uses the sort function where we specify the sorting ordering to be index tie broken by length.

Related