2016-09-22 58 views
-5

有没有一种方法在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]] 
+5

,你想究竟它是排序? –

+0

半开玩笑的答案:切换到Python 2.7,其中允许比较整数和字符串等。 – Kevin

+0

Teemu询问 - 您的预期产量是多少? –

回答

1

Python的比较明智的运营商拒绝为不兼容的类型的变量的工作。决定排序列表的标准,将其封装在函数中,并将其作为key选项传递给sort()。例如,为了由每个元件(字符串)的repr进行排序:

l.sort(key=repr) 

为了通过型的第一排序,然后由内容:

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

后者的优点是号码得到分类的优点数字,按字母顺序排列的字符串等等。如果有两个无法比较的子列表,它仍然会失败,但是您必须决定要做什么 - 只要扩展您的键功能,无论您认为合适。

+0

很高兴听到它,但请注意免责声明:它只是将问题推下了一步。如果您需要使用随机内容对子列表进行排序,则需要特别说明。 – alexis

+0

一个递归/动态的方法将为此工作。 –

+0

@Wayne,为它付出。但它可能不符合OP的预期。谁知道。 – alexis

0

key -argument到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]] 
相关问题