【问题标题】:How to sort a list that contains combined numerical and text value based on the order of numerical value如何根据数值的顺序对包含组合数值和文本值的列表进行排序
【发布时间】:2019-09-11 06:54:39
【问题描述】:

我有一个未排序的列表

['1 Apple', '6 Apple', '2 Apple', '4 Apple', '3 Apple', '170 Apple', 'category']

如何创建一个以升序添加值的列表:

['category', '1 Apple', '2 Apple', '3 Apple', '4 Apple', '6 Apple', '170 Apple']`

【问题讨论】:

  • 它可以包含负数和/或浮点数吗?
  • ['1 Apple','6 Apple','2 Apple','4 Apple','3 Apple','170 Apple','category','book']。在这种情况下你想要什么输出?

标签: python python-3.x list sorting


【解决方案1】:

适用于任何类型的“混合字符串+数字字符串元素”列表的简单解决方案。

import re
s = ['1Apple', '6 Apple', '2 Apple', '4 Apple', '3 Apple', '170 Apple', 'category']
nums = [re.findall('\d+',ss) for ss in s] # extracts numbers from strings
numsint = [int(*n) for n in nums] # returns 0 for the empty list corresponding to the word
sorted_list = [x for y, x in sorted(zip(numsint, s))] # sorts s based on the sorting of nums2

print(sorted_list)
# output
['category', '1Apple', '2 Apple', '3 Apple', '4 Apple', '6 Apple', '170 Apple']

【讨论】:

    【解决方案2】:

    您将使用 sort 或 sorted 指定从字符串中提取该数字的键。

    这是一个快速示例,它不处理所有极端情况(浮点数、负数、无整数排序),但应该足以让您了解总体思路:

    def numeric_key(string):
        splitted = string.split(' ')
        if splitted[0].isdigit():
            return int(splitted[0])
        return -1
    
    my_list.sort(key=numeric_key)
    
    

    【讨论】:

    • 谢谢老兄!我还尝试使用 lambda 函数来摆脱同样有效的“苹果”
    • if splitted 部分是不必要的,因为split 将始终返回一个非空列表:即使字符串无法拆分,也会返回包含原始字符串的列表
    • 为了完全精确:只要指定了分隔符,我的最后一条评论就是正确的。在没有明确指定的情况下拆分空格(等于传递None)时,在拆分空字符串或仅空格时可能会返回一个空列表。在这种情况下,它永远不会是一个空列表
    【解决方案3】:

    我的方式,一行(适用于所有混合类型):

    import re
    s=['1 Apple', '6 Apple', '2 Apple', '4 Apple', '3 Apple', '170 Apple', 'category', 'billy']
    
    x=[i[2] for i in sorted([([float(i) for i in (re.findall(r'\d+',i))],re.findall(r'[^0-9]+',i),i) for i in s])]
    
    ['billy',
     'category',
     '1 Apple',
     '2 Apple',
     '3 Apple',
     '4 Apple',
     '6 Apple',
     '170 Apple']
    

    【讨论】:

      【解决方案4】:

      这可以通过

      s = sorted(s, key=lambda x:int(x.split(' ')[0]))

      但仅当列表包含空格和前面的数值时,由您指定。对于“类别”,我们可以轻松区分它是否遵循上述逻辑。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-29
        • 2016-09-01
        • 1970-01-01
        相关资源
        最近更新 更多