在python中按数字顺序打印输出

我编写了一个程序,该程序一次读取多个文件的最后一行,并将输出打印为元组列表。


    from os import listdir

    from os.path import isfile, join


    import subprocess

    path = "/home/abc/xyz/200/coord_b/"

    filename_last_lines = [[(filename, subprocess.check_output(['tail', '-1', path + 

    filename]))] for filename in [f for f in listdir(path) if isfile(join(path, f)) and 

    f.endswith('.txt')]]


    print(filename_last_lines)

我现在得到的输出是(coord_70.txt,P),(coord_4.txt,R)等等,这是非常随机的。我需要按数字顺序打印它,如(coord_1.txt,R),(coord_2.txt,R)等。你能建议我修改这个代码吗?


互换的青春
浏览 325回答 3
3回答

一只名叫tom的猫

只需在列表上应用排序():”    filename_last_lines = [[(filename, subprocess.check_output(['tail', '-1', path + filename]))] for filename in [f for f in sorted(listdir(path)) if isfile(join(path, f)) and f.endswith('.txt')]]

偶然的你

也许你只需要对文件名进行排序:filename_last_lines = [[(filename, subprocess.check_output(['tail', '-1', path +     filename]))] for filename in sorted([f for f in listdir(path) if isfile(join(path, f)) and     f.endswith('.txt')])]

慕容708150

您将必须使用自定义函数的列表。sortkeyfilename_last_lines.sort(key=lambda x: int(x[0][6:-4]))让我们解码 lambda 的作用。列表的每个元素都是一个元组,因此抓取元组的第一个元素,即文件名。x[0]然后,我们要从文件名中提取数字作为整数,因此:In [1]: x = ('coord_70.txt', 1)Out[1]: ('coord_70.txt', 1)In [2]: int(x[0][6:-4])Out[2]: 70
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python