如何根据数值的顺序对包含数值和文本组合值的列表进行排序

2024-04-27 03:47:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张未分类的单子

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

Tags: apple列表单子category升序未分类
3条回答

这可以通过

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

但仅当列表前面包含空格和数字值时,如您指定的情况。对于“类别”,我们可以很容易地区分它是否遵循上述逻辑。你知道吗

您可以使用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)

简单的解决方案,应该适用于任何类型的“混合字符串只+数字字符串元素”列表。你知道吗

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

相关问题 更多 >