Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python sort by last word in line, different length lines

I have a file that has between 1 or 4 words per line, and I want to sort by the third word in the line. The below code does not work if there isn't a word in the s[2] slot. Is there anything I can do to still sort everything does? Thanks

with open('myfile.txt') as fin:
lines = [line.split() for line in fin]
lines.sort(key=lambda s: s[2])
like image 851
Kiril Alex Ballow Avatar asked Dec 10 '25 00:12

Kiril Alex Ballow


2 Answers

‏You may want to try using the slice syntax

with open('myfile.txt') as fin:
    lines = [line.split() for line in fin]
    lines.sort(key=lambda s: s[2:3]) # will give empty list if there is no 3rd word
like image 170
Yoav Glazner Avatar answered Dec 12 '25 14:12

Yoav Glazner


Try this:

x.sort(key=lambda s: s[2] if len(s) > 2 else ord('z')+1)

That way if there is no s[2] it returns the next thing after 'z' (presumably the last ascii character value in your strings). Feel free to change ord('z')+1 to some other large number

like image 20
Garrett R Avatar answered Dec 12 '25 13:12

Garrett R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!