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

Python 字符串的数字排序

Python 字符串的数字排序

弑天下 2021-07-28 17:49:58
如何让 Python 排序表现得像sort -nGNU coreutils 一样?这是我的images.txt:Vol. 1/Vol. 1 - Special 1/002.pngVol. 1/Chapter 2 example text/002.pngVol. 1/Vol. 1 Extra/002.pngVol. 1/Chapter 2 example text/001.pngVol. 1/Vol. 1 Extra/001.pngVol. 1/Chapter 1 example text/002.pngVol. 1/Vol. 1 - Special 1/001.pngVol. 1/Chapter 1 example text/001.png当我运行这个 Bash 脚本时:#!/bin/bashcat images.txt | sort -n我得到以下输出:Vol. 1/Chapter 1 example text/001.pngVol. 1/Chapter 1 example text/002.pngVol. 1/Chapter 2 example text/001.pngVol. 1/Chapter 2 example text/002.pngVol. 1/Vol. 1 Extra/001.pngVol. 1/Vol. 1 Extra/002.pngVol. 1/Vol. 1 - Special 1/001.pngVol. 1/Vol. 1 - Special 1/002.png但是当我运行这个 Python 脚本时:#!/usr/bin/env python3images = []with open("images.txt") as images_file:    for image in images_file:        images.append(image)images = sorted(images)for image in images:    print(image, end="")我得到以下输出,这不是我需要的:Vol. 1/Chapter 1 example text/001.pngVol. 1/Chapter 1 example text/002.pngVol. 1/Chapter 2 example text/001.pngVol. 1/Chapter 2 example text/002.pngVol. 1/Vol. 1 - Special 1/001.pngVol. 1/Vol. 1 - Special 1/002.pngVol. 1/Vol. 1 Extra/001.pngVol. 1/Vol. 1 Extra/002.png如何使用 Python 获得与使用 Bash 和sort -n.
查看完整描述

2 回答

?
翻过高山走不出你

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

虽然我不是 牛牛专家,它'-'的顺序似乎与 Python 不同。此特定问题的快速解决方法是在排序时替换' - '' '

L = sorted(L, key=lambda x: x.replace(' - ', ' '))


查看完整回答
反对 回复 2021-08-03

没有找到匹配的内容?试试慕课网站内搜索吧

添加回答

代码语言

举报

0/150
提交
取消
微信客服

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

帮助反馈 APP下载

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

公众号

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