【问题标题】:How to sort a list containing alphanumerical data in python如何在python中对包含字母数字数据的列表进行排序
【发布时间】:2021-03-10 12:01:30
【问题描述】:

我查看了许多论坛和主题,但没有一个对我的数据有用。 我的数据类似于

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

我想按数字顺序对其进行排序以获取类似的数据(在这种情况下) AlexJones:7 张牌,JohnSmith:10 张牌,Billybob:19 张牌…… 到目前为止,我所做的一切都导致错误或按字母顺序排序。

【问题讨论】:

    标签: python sorting


    【解决方案1】:

    使用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))
    

    输出

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

    如果上面的代码清单你有两个key函数的例子。

    【讨论】:

      【解决方案2】:

      如果你用空格分割值,卡片的数量总是第三个元素。因此,您可以按空格分割,将此元素转换为 int 并将其用作键:

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

      【讨论】:

        猜你喜欢
        • 2013-10-22
        • 1970-01-01
        • 2022-11-24
        • 1970-01-01
        • 2011-03-14
        • 1970-01-01
        • 2018-04-09
        • 2022-11-23
        • 1970-01-01
        相关资源
        最近更新 更多