我有一个文件,每行有1到4个单词,我想按行中的第三个单词排序。如果s [2]插槽中没有单词,则下面的代码不起作用。有什么我可以做的仍然排序一切吗?感谢
with open('myfile.txt') as fin:
lines = [line.split() for line in fin]
lines.sort(key=lambda s: s[2])
答案 0 :(得分:4)
您可能想尝试使用切片语法
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
答案 1 :(得分:1)
试试这个:
x.sort(key=lambda s: s[2] if len(s) > 2 else ord('z')+1)
那样如果没有s [2],它会在'z'之后返回下一个东西(可能是你字符串中的最后一个ascii字符值)。随意将ord('z')+ 1更改为其他大数
答案 2 :(得分:0)
def sortFileByLastWords(fIn, fOut):
with open (fIn) as fin:
lines = [line.split () for line in fin]
lines.sort (key=lambda s: s[-1]) # make the last word of each line be the key
with open (fOut, "w") as fout:
for film in lines:
fout.write (' '.join (film) + '\n')