python 3中的sort函数

时间:2017-08-26 06:25:24

标签: python python-3.x

我是python的初学者。我排序了一个字符串值列表但是 ' 8,13' ' 8,14' ....和' 9,11' ' 9,12' ....价值观持续到了。是什么导致这个错误? 我在终端输入了这个。

a = ['13,7', '14,7', '15,7', '12,8', '13,8', '14,8', '15,8', '16,8', 
     '11,9', '12,9', '13,9', '16,9', '10,10', '11,10', '12,10', 
     '16,10', '9,11', '10,11', '11,11', '16,11', '9,12', '10,12', 
     '16,12', '8,13', '9,13', '10,13', '15,13', '16,13', '8,14', 
     '9,14', '15,14', '16,14', '17,14', '8,15', '9,15', '14,15', 
     '16,15', '17,15', '18,15', '19,15', '8,16', '9,16', '12,16', 
     '13,16', '17,16', '18,16', '19,16', '8,17', '9,17', '10,17', 
     '11,17', '12,17', '9,18', '10,18', '11,18']

a.sort()

a
#['10,10', '10,11', '10,12', '10,13', '10,17', '10,18', '11,10', 
# '11,11', '11,17', '11,18', '11,9', '12,10', '12,16', '12,17', 
# '12,8', '12,9', '13,16', '13,7', '13,8', '13,9', '14,15', '14,7', 
# '14,8', '15,13', '15,14', '15,7', '15,8', '16,10', '16,11', '16,12', 
# '16,13', '16,14', '16,15', '16,8', '16,9', '17,14', '17,15', 
# '17,16', '18,15', '18,16', '19,15', '19,16', '8,13', '8,14', '8,15', 
# '8,16', '8,17', '9,11', '9,12', '9,13', '9,14', '9,15', '9,16', 
# '9,17', '9,18']

3 个答案:

答案 0 :(得分:1)

您的列表元素属于str类型,因此您需要在排序之前将它们转换为int元组,或者可以使用lambda作为key参数sort 1}}即时转换的方法为:

>>> a.sort(key=lambda x:map(int, x.split(",")))
>>> ['8,13', '8,14', '8,15', '8,16', '8,17', '9,11', '9,12', '9,13', '9,14', '9,15', '9,16', '9,17', '9,18', '10,10', '10,11', '10,12', '10,13', '10,17', '10,18', '11,9', '11,10', '11,11', '11,17', '11,18', '12,8', '12,9', '12,10', '12,16', '12,17', '13,7', '13,8', '13,9', '13,16', '14,7', '14,8', '14,15', '15,7', '15,8', '15,13', '15,14', '16,8', '16,9', '16,10', '16,11', '16,12', '16,13', '16,14', '16,15', '17,14', '17,15', '17,16', '18,15', '18,16', '19,15', '19,16']

答案 1 :(得分:1)

这应该这样做。逗号需要额外的步骤。

a = [float(i.replace(',', '.')) for i in a]
a.sort()

参考这篇文章:How can I convert a string with dot and comma into a float number in Python以实际的Pythonic方式处理使用逗号而不是小数点的数字。

答案 2 :(得分:0)

我猜你正在寻找的是自然的。使用natsort第三方库并排序。

>>> import natsort
>>> natsort.natsorted(a)
['8,13', '8,14', '8,15', '8,16', '8,17', '9,11', '9,12', '9,13', '9,14', '9,15', '9,16', '9,17', '9,18', '10,10', '10,11', '10,12', '10,13', '10,17', '10,18', '11,9', '11,10', '11,11', '11,17', '11,18', '12,8', '12,9', '12,10', '12,16', '12,17', '13,7', '13,8', '13,9', '13,16', '14,7', '14,8', '14,15', '15,7', '15,8', '15,13', '15,14', '16,8', '16,9', '16,10', '16,11', '16,12', '16,13', '16,14', '16,15', '17,14', '17,15', '17,16', '18,15', '18,16', '19,15', '19,16']

排序是在字符串之间。它逐字母地比较字符串。例如,当比较字符串' 10,10'和' 9,18'它的第一个比较' 1'和' 9'然后' 0' 0和','等等。这就是你没有得到理想结果的原因。