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:
(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.