排序整数和字符串的混合列表

2024-06-16 13:43:49 发布

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

我试图对下面的int和string混合列表进行排序,但是得到的却是TypeError。我想要的输出顺序是先对整数排序,然后对字符串排序。在

x=[4,6,9,'ashley','drooks','chay','poo','may']
>>> x.sort()
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    x.sort()
TypeError: '<' not supported between instances of 'str' and 'int'

Tags: 字符串列表string排序顺序整数sortmay
2条回答

可以将自定义键函数传递给^{}

x = [4,6,9,'ashley','drooks','chay','poo','may']
x.sort(key=lambda v: (isinstance(v, str), v))

# result:
# [4, 6, 9, 'ashley', 'chay', 'drooks', 'may', 'poo']

此键函数将列表中的每个元素映射到一个元组,其中第一个值是布尔值(True表示字符串,False表示数字),第二个值是元素本身,如下所示:

^{pr2}$

然后使用这些元组对列表进行排序。因为False < True,这使得整数在字符串之前排序。具有相同布尔值的元素将按元组中的第二个值排序。在

我从你的评论中可以看出,你希望先对整数排序,然后对字符串排序。在

因此,我们可以对两个单独的列表进行排序,并按如下方式将它们连接起来:

x=[4,6,9,'ashley','drooks','chay','poo','may']
intList=sorted([i for i in x if type(i) is int])
strList=sorted([i for i in x if type(i) is str])
print(intList+strList)

输出:

[4, 6, 9, 'ashley', 'chay', 'drooks', 'may', 'poo']

相关问题 更多 >