sorting list in python

烂漫一生 提交于 2019-12-04 00:49:52

问题


if I have a list of strings e.g. ["a143.txt", "a9.txt", ] how can I sort it in ascending order by the numbers in the list, rather than by the string. I.e. I want "a9.txt" to appear before "a143.txt" since 9 < 143.

thanks.


回答1:


It's called "natural sort order", From http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html

Try this:

import re 

def sort_nicely( l ): 
  """ Sort the given list in the way that humans expect. 
  """ 
  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 ) 



回答2:


Use list.sort() and provide your own function for the key argument. Your function will be called for each item in the list (and passed the item), and is expected to return a version of that item that will be sorted.

See http://wiki.python.org/moin/HowTo/Sorting/#Key_Functions for more information.




回答3:


If you want to completely disregard the strings, then you should do

import re
numre = re.compile('[0-9]+')
def extractNum(s):
    return int(numre.search(s).group())

myList = ["a143.txt", "a9.txt", ]
myList.sort(key=extractNum)



回答4:


>>> paths = ["a143.txt", "a9.txt"]
>>> sorted(paths, key=lambda s: int(re.search("\d+", s).group()))
['a9.txt', 'a143.txt']

More generic, if you want it to work also for files like: a100_32_12 (and sorting by numeric groups):

>>> paths = ["a143_2.txt", "a143_1.txt"]
>>> sorted(paths, key=lambda s: map(int, re.findall("\d+", s)))
['a143_1.txt', 'a143_1.txt']



回答5:


list.sort() is deprecated (see Python.org How-To) . sorted(list, key=keyfunc) is better.

import re

def sortFunc(item):
  return int(re.search(r'[a-zA-Z](\d+)', item).group(1))

myList = ["a143.txt", "a9.txt"]

print sorted(myList, key=sortFunc)


来源:https://stackoverflow.com/questions/5491913/sorting-list-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!