Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 对包含字符串、浮点和整数的列表进行排序_Python_Python 3.x_Sorting - Fatal编程技术网

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

Python 对包含字符串、浮点和整数的列表进行排序,python,python-3.x,sorting,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

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

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

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

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

后者的优点是数字按数字排序,字符串按字母顺序排序等。如果有两个子列表无法比较,则仍然会失败,但是,您必须决定要做什么——只需扩展您认为合适的键函数。

列表的
-参数。sort
sorted
可用于按您需要的方式对其进行排序,首先您需要定义如何对类型进行排序,最简单(可能最快)是一个以类型为键,以顺序为值的字典

# define a dictionary that gives the ordering of the types
priority = {int: 0, float: 0, str: 1, bool: 2, list: 3}
为了实现这一点,我们可以使用
元组
列表
首先比较第一个元素,如果相等,则比较第二个元素,如果相等,则比较第三个元素(依此类推)

最后,您可以对输入进行排序,我将对其进行洗牌,因为它已经排序(据我所知,您的问题):


你到底希望它是如何排序的?半开玩笑的回答:切换到Python 2.7,在那里可以比较整数和字符串等。正如Teemu所问的-你期望的输出是什么?我希望它按值按浮点和整数排序,然后按类型排序:首先是浮点和整数,然后是字符串,然后是布尔值,然后是列表。我想使用Python2.7,但我不被允许…那么哪一个更大,
[2,3,4,3,3,4]],5]
“titi”
?很高兴听到这个消息,但请注意免责声明:它只会将问题推下一步。如果需要对随机内容的子列表进行排序,则需要对其进行特殊处理。@Wayne,开始吧。但这可能与OP的预期不符。谁知道呢。
# define a dictionary that gives the ordering of the types
priority = {int: 0, float: 0, str: 1, bool: 2, list: 3}
# 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]]