简体   繁体   中英

How to sort the list in the specific ordering

I am working on the scramble sorting function, which takes two arguments:

  1. a list of strings to sort
  2. a string showing the ordering of the letters in the alphabet (not necessarily the standard ordering).

It returns the list of strings sorted according the second argument.

For example:

scramble(['abc', 'bac', 'abb'], 'cba')

should return

['bac', 'abc', 'abb']

The second argument in this call shows for comparison purposes, c < b < a. So words starting with 'b' come before words starting with 'a'; and 'abc' comes before 'abb' because disregarding the common prefix ('ab'), 'c' comes before 'b'.

def scramble(l : [str], ordering : str) -> [str]:
    for i in ordering:
        for h in l:
            l.sort(key = h.index(i))
            break
    return l

My code does not work, I only got the general idea to sort the list by the index of the letter(according to the ordering) of the item in the list. can someone help me to fix my code?

def scramble(words, order):
    return sorted(words, key = lambda word: [order.index(char) for char in word])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM