Eric
Eric

Reputation: 91

How can I sort this data using Python?

I am writing a program that reads in a text file containing two columns.

It needs to sort the first column based on the last character in it and output to a new file. If the last characters in the first set is the same then it sorts by the first character. If the last and first character are the same, then it sorts by the middle character. For example, the data being read from the file would be:

ac  123 
aba 456 
abd 456 
bda 123 
baa 123

For the first row, "a" is the first character and "c" is the last character, there is no middle character.

The output should look like this:

aba 456 
baa 123 
bda 123 
ac  123 
abd 456

So far I have been able to read in the file and split it up, however I am stuck on figuring out how to sort it alphabetically. Can someone suggest what might help me?

This is my code so far:

f = open('example.txt','r')
new = []
for row in f.readlines():
     data = row.split()
     print(data)

The output looks like:

['ac', '123']
['aba', '456']
['abd', '456']
['bda', '123']
['baa', '123']

Am I going in the right direction?

I also was reading about something called lambda and I'm not sure if that would be useful or not because I have never used it in Python.

Upvotes: 0

Views: 150

Answers (1)

Tom Zych
Tom Zych

Reputation: 13576

Read the data into a list, then sort with key=keyfunc. Pardon me not giving you a complete solution, but this smells like homework, so.

def keyfunc(s):
    firstword = s.split()[0]
    char1 = firstword[-1]
    char2 = firstword[0]
    char3 = firstword[1] if len(firstword) == 3 else ""
    return char1 + char2 + char3

Upvotes: 3

Related Questions