为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

互换的青春 2022-09-27 16:35:54
我编写了一个程序,该程序一次读取多个文件的最后一行,并将输出打印为元组列表。    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)等。你能建议我修改这个代码吗?
查看完整描述

3 回答

?
一只名叫tom的猫

TA贡献1906条经验 获得超3个赞

只需在列表上应用排序():”


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


查看完整回答
反对 回复 2022-09-27
?
偶然的你

TA贡献1841条经验 获得超3个赞

也许你只需要对文件名进行排序:


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


查看完整回答
反对 回复 2022-09-27
?
慕容708150

TA贡献1831条经验 获得超4个赞

您将必须使用自定义函数的列表。sortkey


filename_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


查看完整回答
反对 回复 2022-09-27
  • 3 回答
  • 0 关注
  • 324 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号