简体   繁体   中英

Reversing order of a list and then sorting in lexicographical order

I need to make a code that sorts a list of words and puts them in lexicographical order from reverse. For example, given the list ["harry", "harra", harrb"] I need a way to reverse each word so the list becomes ["yrrah", "arrah","brrah"] . Then I need to sort it by lexicographical order and reverse it back to its original order. So it would look like ["harra", "harrb", "harry"] . Im taking words from a file 'ifile' but for this code I'm only ordering words with a certain number of letters "n".

Here is my code so far:

def getRhymeSortedCount(n,ifile,file):
    word_list = []
    for word in ifile:
        if len(word) == n:
            word_list.append(word.strip())
    arr = word_list
    arr.sort(key = lambda x : x[::-1])
    ofile.write("\n".join(word_list))

it correctly orders the words by their last letter, but isnt taking the words with number of letters = "n" how can i change my len statement to grab only the words with n letters?

Specify the key to sort to be the reversed string

word_list = ["harry","harra", "harrb"]
word_list.sort(key=lambda str: str[::-1])

Use a simple lambda function -

arr = ["harry","harra", "harrb"]

arr.sort(key = lambda x : x[::-1])

print(arr)

Output -

['harra', 'harrb', 'harry']

feels like you want someone to do you homework for you - so here's an answer you'll have to unpack a little to understand

word_list = ['harry', 'harra', 'harrb', "ignore_me"]
[y[::-1] for y in sorted([ x[::-1] for x in word_list if len(x) == 5])]

things to learn here:

  • list comprehension [ f(x) for x in list_of_xs if expression ]
  • you can slice strings as characters lists (and in reverse, too)
  • sorted(mylist) returns a sorted version of the list
  • while you're here check out reversed(mylist), even though its not used here. you can nest these : reversed(sorted(mylist)) - neat! (but not used in my solution)

(ohh, i like the lambda answers)

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