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])
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With