python 排序梳理

sort()方法:(用于列表)
sort(self, /, *, key=None, reverse=False)
sorted()方法:(任意可迭代对象)
sorted(iterable, /, *, key=None, reverse=False)

#   1.排序的元素不能两种不同类型的元素进行排序
>>>list1=[2,1,(3,4),6]
>>> list1.sort()
Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
    list1.sort()
TypeError: '<' not supported between instances of 'tuple' and 'int'
>>> list2=[6,1,'python',3]
>>> list2.sort()
Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    list2.sort()
TypeError: '<' not supported between instances of 'str' and 'int'

由上述两个例子可得出,只有两个数据类型相同的数据才能进行比较。

对list中的字符串进行排序 如果他内部同时含有英文字母和中文的话,优先对英文字母进行排序,再按照中文的ascl码排序,代码如下:

>>> list1=['zero','零','two','一']
>>> list1.sort()
>>> list1
['two', 'zero', '一', '零']


>>> list1.sort(reverse=True)
>>> list1
['零', '一', 'zero', 'two']

接下来聊聊key关键字的用法:

>>> # 1.对嵌套列表的排序
>>> list1=[[9,1],[9,2],[3,3],[1,2]]
>>> list1.sort(key=lambda x:x{1])
SyntaxError: invalid syntax
>>> list1.sort(key=lambda x:x[1])
>>> list1
[[9, 1], [9, 2], [1, 2], [3, 3]]

上述的 lambda x:x[1] 是将list1中的可迭代元素的第二个元素取出来进行比较,因为list1的每个元素仍然是列表。(lambda 是匿名函数)

当然我们也会遇到 [[9,9],[9,8],[8,7],[8,3]] 这种类型的数据进行排序,按照普通方法为:

>>> list2=[[9,9],[9,8],[8,7],[8,3]]
>>> list2.sort(key=lambda x:x[0])
>>> list2
[[8, 7], [8, 3], [9, 9], [9, 8]]

我们不难发现,虽然list2的每个列表,都是按照第一个元素升序排序,但是第二个就是无序的了。

所以加入我们想让他像新华字典的那样的排序的话我们可以把他转成str类型:

>>> list2=[[9,9],[9,8],[8,7],[8,3]]
>>> list2.sort(key=lambda x:str(x[0])+str(x[1]))
>>> list2
[[8, 3], [8, 7], [9, 8], [9, 9]]

相比较sort只适用于list的局限性,sorted就可以很好的解决其他可迭代对象的排序问题:
1.例如对字典的排序,我们便不再需要先将他转成list

>>> dict1={9:'张三',8:'李四',10:'赵五',4:'王二'}
>>> list_dict1=sorted(dict1)
[4, 8, 9, 10]

当然返回的对象仍然是list的形式。
sorted括号内只填dict1时,返回的默认为升序的键的列表,此时我们便可通过list_dict1的元素去访问排序后的字典。

我们也可以使用dict下的items()方法来直接获得(键,值)tuple:

>>> list2_dict1=sorted(dict1.items())
[(4, '王二'), (8, '李四'), (9, '张三'), (10, '赵五')]

此时便可直接通过index来访问对应元素。

如若想不是想对键进行排序,而是值得话,我们可以用以下方法:

>>> list3_dict1=sorted(dict1.items(),key=lambda x:x[1])
[(9, '张三'), (8, '李四'), (4, '王二'), (10, '赵五')]
[/code]

所以综合来说,sorted的范围比sort的应用范围更加广,可能我还没有总结到位,后续会继续补充。

第一次写博客,希望坚持下去加油!!

发布了1 篇原创文章 · 获赞 4 · 访问量 105

猜你喜欢

转载自blog.csdn.net/m0_46159423/article/details/105538530