简体   繁体   中英

How to sort a list containing alphanumerical data in python

I have looked at many forums and threads and none of them worked for my data. My data is Something like

list = ["JohnSmith : 10 cards", "AlexJones : 7 cards", "BillyBob : 19 cards", "JoeBlogs : 21 cards"...]

and i want to sort it by numerical order to get the data like (in this case) AlexJones: 7 cards, JohnSmith: 10 cards, Billybob: 19 cards... Everything I have tried so far has resulted in errors or sorting by alphabetical order.

Use the key parameter, of sorted , for example:

import re

lst = ["JohnSmith : 10 cards", "AlexJones : 7 cards", "BillyBob : 19 cards", "JoeBlogs : 21 cards"]


def only_one_digit_group_key(s):
    """This function filters out non-digit characters, assumes only one contiguous group of digits"""
    return int(''.join([e for e in s if e.isdigit()]))


def regex_key(s):
    """This function will extrac the digits from the pattern group of digits followed by cards"""
    return int(re.search(r'(\d+)\s+cards', s).group(1))


print(sorted(lst, key=only_one_digit_group_key))

print(sorted(lst, key=regex_key))

Output

['AlexJones : 7 cards', 'JohnSmith : 10 cards', 'BillyBob : 19 cards', 'JoeBlogs : 21 cards']
['AlexJones : 7 cards', 'JohnSmith : 10 cards', 'BillyBob : 19 cards', 'JoeBlogs : 21 cards']

If the above code listing you have two examples of key functions.

If you split the value by a space, the number of cards is always the third element. So you could split by space, convert this element to an int and use it as a key:

lst.sort(key = lambda x : int(x.split(' ')[2]))

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