Python字符串的数字排序
如何使Python排序与GNU coreutils中的排序-n类似 这是我的Python字符串的数字排序,python,sorting,gnu,Python,Sorting,Gnu,如何使Python排序与GNU coreutils中的排序-n类似 这是我的images.txt: Vol. 1/Vol. 1 - Special 1/002.png Vol. 1/Chapter 2 example text/002.png Vol. 1/Vol. 1 Extra/002.png Vol. 1/Chapter 2 example text/001.png Vol. 1/Vol. 1 Extra/001.png Vol. 1/Chapter 1 example text/002.
images.txt
:
Vol. 1/Vol. 1 - Special 1/002.png
Vol. 1/Chapter 2 example text/002.png
Vol. 1/Vol. 1 Extra/002.png
Vol. 1/Chapter 2 example text/001.png
Vol. 1/Vol. 1 Extra/001.png
Vol. 1/Chapter 1 example text/002.png
Vol. 1/Vol. 1 - Special 1/001.png
Vol. 1/Chapter 1 example text/001.png
运行此Bash脚本时:
#!/bin/bash
cat images.txt | sort -n
我得到以下输出:
Vol. 1/Chapter 1 example text/001.png
Vol. 1/Chapter 1 example text/002.png
Vol. 1/Chapter 2 example text/001.png
Vol. 1/Chapter 2 example text/002.png
Vol. 1/Vol. 1 Extra/001.png
Vol. 1/Vol. 1 Extra/002.png
Vol. 1/Vol. 1 - Special 1/001.png
Vol. 1/Vol. 1 - Special 1/002.png
但是当我运行这个Python脚本时:
#!/usr/bin/env python3
images = []
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.png
Vol. 1/Chapter 1 example text/002.png
Vol. 1/Chapter 2 example text/001.png
Vol. 1/Chapter 2 example text/002.png
Vol. 1/Vol. 1 - Special 1/001.png
Vol. 1/Vol. 1 - Special 1/002.png
Vol. 1/Vol. 1 Extra/001.png
Vol. 1/Vol. 1 Extra/002.png
如何使用Python获得与使用Bash和sort-n
相同的结果?虽然我不是专家,但与Python相比,'-'
的顺序似乎有所不同。此特定问题的快速解决方法是在排序时将'-'
替换为'
:
L = sorted(L, key=lambda x: x.replace(' - ', ' '))
您可能还想考虑一个替换所有非字母数字字符
的lambda。images = sorted(images, key=lambda x: re.sub('[^A-Za-z\d]+', '', x))
我不确定是否有一个内置的方法,可能是重复的,似乎
-
被区别对待。可能排序(L,key=lambda x:x.replace('-','')
?我缺少你问题中的“数字”部分。两个例子中的数字排序相同。@jpp谢谢,这很有效。你能把你的解决方案作为答案提交给我吗?