本文介绍了对python列表进行排序以使字母位于数字之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手,我正在寻找一种对列表进行排序的方法,该列表将单词放在数字之前.

I'm pretty new to python and I'm looking for a way to sort a list placing words before numbers.

我了解您可以使用sort执行以下操作:

I understand you can use sort to do the following :

a = ['c', 'b', 'd', 'a']
a.sort()
print(a)
['a', 'b', 'c', 'd']

b = [4, 2, 1, 3]
b.sort()
print(b)
[1, 2, 3, 4]

c = ['c', 'b', 'd', 'a', 4, 2, 1, 3]
c.sort()
print(c)
[1, 2, 3, 4, 'a', 'b', 'c', 'd']

但是我想对c进行排序以生成:

However I'd like to sort c to produce :

['a', 'b', 'c', 'd', 1, 2, 3, 4]

预先感谢

推荐答案

您可以提供一个自定义的key参数,该参数为字符串提供的值比为整数提供的值低:

You could provide a custom key argument which gives a lower value to strings than it does to ints:

>>> c = ['c', 'b', 'd', 'a', 4, 2, 1, 3]
>>> c.sort(key = lambda item: ([str,int].index(type(item)), item))
>>> c
['a', 'b', 'c', 'd', 1, 2, 3, 4]

这篇关于对python列表进行排序以使字母位于数字之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 07:18
查看更多