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

时间:2018-04-14 09:04:06

标签: python python-3.x list sorting mixed

我正在尝试对以下混合的整数和字符串列表进行排序,但却得到了一个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'

3 个答案:

答案 0 :(得分:8)

您可以将自定义键功能传递给list.sort

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表示数字),第二个值是元素本身,如这样:

>>> [(isinstance(v, str), v) for v in x]
[(False, 4), (False, 6), (False, 9), (True, 'ashley'), (True, 'chay'),
 (True, 'drooks'), (True, 'may'), (True, 'poo')]

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

答案 1 :(得分:1)

我可以从你的评论中看到你想要整数先排序然后排序。

因此我们可以对两个单独的列表进行排序并按如下方式加入它们:

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

答案 2 :(得分:1)

带有功能键

def func(i):
    return isinstance(i, str), i

stuff = ['Tractor', 184 ,'Lada', 11 ,'Ferrari', 5 , 'Chicken' , 68]
stuff.sort(key=func)

for x in stuff:
    print(x)

将类型str更改为int以首先获取字符串。

相关问题