簡體   English   中英

如何對 python 中包含字母數字數據的列表進行排序

[英]How to sort a list containing alphanumerical data in python

我查看了許多論壇和主題,但沒有一個對我的數據有用。 我的數據類似於

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

我想按數字順序對其進行排序以獲取數據,例如(在這種情況下)AlexJones:7 張卡片,JohnSmith:10 張卡片,Billybob:19 張卡片......到目前為止我嘗試的所有內容都導致錯誤或按字母順序排序命令。

使用sortedkey參數,例如:

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']

如果上面的代碼清單你有兩個關鍵功能的例子。

如果用空格分割值,則卡片的數量始終是第三個元素。 因此,您可以按空格分割,將此元素轉換為 int 並將其用作鍵:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM