简体   繁体   中英

How can I sort list of strings in specific order?

Let's say I have such a list:

['word_4_0_w_7',
 'word_4_0_w_6',
 'word_3_0_w_10',
 'word_3_0_w_2']

and I want to sort them according to number that comes after "word" and according to number after "w". It will look like this:

   ['word_3_0_w_2',
     'word_3_0_w_10',
     'word_4_0_w_6',
     'word_4_0_w_7']

What comes in mind is to create a bunch of list and according to index after "word" stuff them with sorted strings according "w", and then merge them.

Is in Python more clever way to do it?

Use Python's key functionality, in conjunction with other answers:

def mykey(value):
    ls = value.split("_")
    return int(ls[1]), int(ls[-1])

newlist = sorted(firstlist, key=mykey)
## or, if you want it in place:
firstlist.sort(key=mykey)

Python will be more efficient with key vs cmp .

You can use a function to extract the relevant parts of your string and then use those parts to sort:

a = ['word_4_0_w_7', 'word_4_0_w_6', 'word_3_0_w_10', 'word_3_0_w_2']

def sort_func(x):
    parts = x.split('_');
    sort_key = parts[1]+parts[2]+"%02d"%int(parts[4])
    return sort_key

a_sorted = sorted(a,key=sort_func)

The expression "%02d" %int(x.split('_')[4]) is used to add a leading zero in front of second number otherwise 10 will sort before 2 . You may have to do the same with the number extracted by x.split('_')[2] .

You can provide a function to the sort() method of list objects:

l = ['word_4_0_w_7',
     'word_4_0_w_6',
     'word_3_0_w_10',
     'word_3_0_w_2']

def my_key_func(x):
    xx = x.split("_")
    return (int(xx[1]), int(xx[-1]))
l.sort(key=my_key_func)

Output:

print l
['word_3_0_w_2', 'word_3_0_w_10', 'word_4_0_w_6', 'word_4_0_w_7']

edit : Changed code according to comment by @dwanderson ; more info on this can be found here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM