Python 按行中的最后一个单词排序,不同长度的行



我有一个文件,每行有 1 到 4 个单词,我想按行中的第三个单词排序。如果 s[2] 插槽中没有单词,则以下代码不起作用。我能做些什么来仍然对所有事情进行排序?谢谢

with open('myfile.txt') as fin:
lines = [line.split() for line in fin]
lines.sort(key=lambda s: s[2])

您可能想尝试使用切片语法

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

试试这个:

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

这样,如果没有 s[2],它将返回 'z' 之后的下一件事(大概是字符串中的最后一个 ascii 字符值)。 随意将 ord('z')+1 更改为其他一些大数字

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')

最新更新