在Python中对字符串列表排序并将数字放在字母后面
我有一个字符串的列表,想要对它进行排序。
默认情况下,字母的值比数字(或者字符串形式的数字)要大,这样在排序后,字母会排在最后面。
>>> 'a' > '1'
True
>>> 'a' > 1
True
我希望能把所有以数字开头的字符串放到列表的底部。
举个例子:
未排序的列表:
['big', 'apple', '42nd street', '25th of May', 'subway']
Python默认的排序结果:
['25th of May', '42nd street', 'apple', 'big', 'subway']
我想要的排序结果:
['apple', 'big', 'subway', '25th of May', '42nd street']
1 个回答
14
>>> a = ['big', 'apple', '42nd street', '25th of May', 'subway']
>>> sorted(a, key=lambda x: (x[0].isdigit(), x))
['apple', 'big', 'subway', '25th of May', '42nd street']
Python的排序功能有一个可选的key
参数,这个参数让你可以指定一个函数,在排序之前先对数据进行处理。元组(tuple)会先根据第一个元素进行排序,如果第一个元素相同,就会根据第二个元素排序,以此类推。
你可以在这里了解更多关于排序的内容。