对整数和字符串的混合列表进行排序 [英] Sorting a mixed list of ints and strings

查看:89
本文介绍了对整数和字符串的混合列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对以下混合的整数和字符串列表进行排序,但是却得到了TypeError.我想要的输出顺序是先对整数排序,再对字符串排序.

I am trying to sort the following mixed list of ints and strings, but getting a TypeError instead. My desired output order is sorted integers then sorted strings.

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'

推荐答案

您可以将自定义键函数传递给

You can pass a custom key function to 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),第二个值是元素本身,如下所示:


This key function maps each element in the list to a tuple in which the first value is a boolean (True for strings and False for numbers) and the second value is the element itself, like this:

>>> [(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,这使得整数可以在字符串之前排序.然后,将具有相同布尔值的元素按元组中的第二个值进行排序.

These tuples are then used to sort the list. Because False < True, this makes it so that integers are sorted before strings. Elements with the same boolean value are then sorted by the 2nd value in the tuple.

这篇关于对整数和字符串的混合列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆