的key
-argument到list.sort
或sorted
可以用于你需要的方式对其进行排序,首先你需要确定你如何要订购的类型,最简单的(也可能最快)与类型作为键的字典和秩序价值
# define a dictionary that gives the ordering of the types
priority = {int: 0, float: 0, str: 1, bool: 2, list: 3}
为了使这项工作可以使用tuples
和lists
首先比较的第一个元素进行比较,事实上,如果相等比较的第二个元素,如果这等于比第三(依此上)。
# 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]]
,你想究竟它是排序? –
半开玩笑的答案:切换到Python 2.7,其中允许比较整数和字符串等。 – Kevin
Teemu询问 - 您的预期产量是多少? –