我的程序读入从文件名parsing的数字。 我想要它的顺序是如何,但在这个例子中,列表为500,4000,7000。我的命名约定应该如何实现呢? 也就是说,当我递增数字的时候,它从小到大列出来。
我真正想要的是它按排名(这里从零开始)进行sorting,然后按递增的数字对它进行sorting.. 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
我将数据逐个文件附加到各种arrays。 不幸的是,如果我不能按请求的顺序对文件进行sorting,这对我来说是非常糟糕的。 也许我的问题是转向开发一个自定义的方法来读取我提供的sorting约束下的文件。
从博客链接的博客评论 :
>>> 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
而不是修改原来的list
:
>>> 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')