我的程序读入从文件名解析的数字。我想要它的确切排序,但是,在这个例子中,列表为500,4000,7000。我的命名约定应该如何实现呢?也就是说,当我增加数字时,它会从最小到最高列出它。
我真正想要的是它按排名排序(这里从零开始),然后按递增数字排序.. 500,5000,7000。
LOG-rank-0-die-10-delay-500.txt
LOG-rank-0-die-10-delay-4000.txt
LOG-rank-0-die-10-delay-7000.txt
LOG-rank-1-die-10-delay-500.txt
LOG-rank-1-die-10-delay-4000.txt
LOG-rank-1-die-10-delay-7000.txt
LOG-rank-2-die-10-delay-500.txt
LOG-rank-2-die-10-delay-4000.txt
LOG-rank-2-die-10-delay-7000.txt
for filenamelogs in sorted(os.listdir(log_directory)):
for each_line in filenamelogs:
#various file parsing activity
我将逐个文件的数据附加到各种数组。不幸的是,如果我无法按照请求的顺序对文件进行排序,这对我来说太可怕了。也许我的问题转向开发一种自定义方法来读取我提供的排序约束下的文件。
答案 0 :(得分:5)
来自对blog中链接的博客的评论:
>>> import re
>>> def sort_nicely(l):
... """
... Sort the given list in the way that humans expect. Modifies the original list.
... """
... convert = lambda text: int(text) if text.isdigit() else text
... alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
... l.sort(key=alphanum_key)
...
>>> mylist = ['LOG-rank-0-die-10-delay-500.txt',
... 'LOG-rank-0-die-10-delay-4000.txt',
... 'LOG-rank-0-die-10-delay-7000.txt',
... 'LOG-rank-1-die-10-delay-500.txt',
... 'LOG-rank-1-die-10-delay-4000.txt',
... 'LOG-rank-1-die-10-delay-7000.txt',
... 'LOG-rank-2-die-10-delay-500.txt',
... 'LOG-rank-2-die-10-delay-4000.txt',
... 'LOG-rank-2-die-10-delay-7000.txt']
>>> sort_nicely(mylist)
>>> print(*mylist, sep='\n')
LOG-rank-0-die-10-delay-500.txt
LOG-rank-0-die-10-delay-4000.txt
LOG-rank-0-die-10-delay-7000.txt
LOG-rank-1-die-10-delay-500.txt
LOG-rank-1-die-10-delay-4000.txt
LOG-rank-1-die-10-delay-7000.txt
LOG-rank-2-die-10-delay-500.txt
LOG-rank-2-die-10-delay-4000.txt
LOG-rank-2-die-10-delay-7000.txt
要return
新的已排序的list
,而不是修改原来的{<1}}:
>>> def sort_nicely(l):
... """
... Sort the given list in the way that humans expect. Returns a new list.
... """
... convert = lambda text: int(text) if text.isdigit() else text
... alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
... return sorted(l, key=alphanum_key)
...
>>> newlist = sort_nicely(mylist)
>>> print(*newlist, sep='\n')