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

时间:2019-09-11 06:54:39

标签: python python-3.x list sorting

我有一个未排序的列表

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

4 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:2)

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

这是一个快速的示例,它不能处理所有极端情况(浮点数,负数,无整数顺序),但足以让您了解一般的想法:

s

答案 2 :(得分:2)

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

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

答案 3 :(得分:1)

这可以通过

完成

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

但是仅当list包含空格和数字值时,这取决于您的指定。对于“类别”,我们可以很容易地区分是否遵循上述逻辑。