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']
这可以通过
s = sorted(s, key=lambda x:int(x.split(' ')[0]))
但仅当列表前面包含空格和数字值时,如您指定的情况。对于“类别”,我们可以很容易地区分它是否遵循上述逻辑。你知道吗
您可以使用sort或sorted指定从字符串中提取数字的键。你知道吗
这是一个快速的示例,它不能处理所有的角点情况(浮点、负数、无整数排序),但应该足以让您了解总体思路:
简单的解决方案,应该适用于任何类型的“混合字符串只+数字字符串元素”列表。你知道吗
相关问题 更多 >
编程相关推荐