对包含字符串,浮点数和整数的列表进行排序

时间:2016-09-22 14:58:26

标签: python python-3.x sorting

Python中有没有办法对列表中的字符串,浮点数和整数进行排序?

我尝试使用list.sort()方法但当然没有用。

以下是我想要排序的列表示例:

[2.0, True, [2, 3, 4, [3, [3, 4]], 5], "titi", 1]

我希望它按值浮点数和整数排序,然后按类型排序:先浮点数和整数,然后是字符串,然后是布尔值,然后是列表。我想使用Python 2.7,但我不允许......

预期产出:

[1, 2.0, "titi", True, [2, 3, 4, [3, [3, 4]], 5]]

2 个答案:

答案 0 :(得分:1)

Python的比较运算符明智地拒绝为不兼容类型的变量工作。确定对列表进行排序的标准,将其封装在函数中并将其作为sort()选项传递给repr。例如,要按每个元素的l.sort(key=repr) (字符串)排序:

l.sort(key=lambda x: (str(type(x)), x))

首先按类型排序,然后按内容排序:

var alamoManager = Alamofire.SessionManager

后者的优点是数字按字母顺序排序,字符串按字母排序等。如果有两个无法比较的子列表,它仍然会失败,但是你必须决定做什么 - 只需扩展你的关键功能然而你看得合适。

答案 1 :(得分:0)

key - list.sortsorted的参数可用于按您需要的方式对其进行排序,首先您需要定义如何订购类型,最简单(并且可能最快)是一个字典,类型为键,顺序为值

# define a dictionary that gives the ordering of the types
priority = {int: 0, float: 0, str: 1, bool: 2, list: 3}

为了完成这项工作,可以使用tupleslists比较的事实,首先比较第一个元素,如果相等,则比较第二个元素,如果相等则比较第三(等等)。

# Define a function that converts the items to a tuple consisting of the priority
# and the actual value
def priority_item(item):
    return priority[type(item)], item

最后,您可以对输入进行排序,我会将其改组,因为它已经排序(据我了解您的问题):

>>> l = [1, 2.0, "titi", True, [2, 3, 4, [3, [3, 4]], 5]]
>>> import random
>>> random.shuffle(l)
>>> print(l)
[True, [2, 3, 4, [3, [3, 4]], 5], 'titi', 2.0, 1]

>>> # Now sort it
>>> sorted(l, key=priority_item)
[1, 2.0, 'titi', True, [2, 3, 4, [3, [3, 4]], 5]]