python列表排序之sort(),sorted()和reverse()

sort()

正序

sort()可以按字母的顺序来对列表进行永久性排序(改变列表自身的排序):

list_1 = ['one', 'two', 'three', 'four', 'five']
print(list_1)

list_1.sort()
print(list_1)

现在list_1列表中有几个首字母相同的元素,那是怎么排序的呢?

['one', 'two', 'three', 'four', 'five']
['five', 'four', 'one', 'three', 'two']

我们可以看出,当首字母一样时,sort()会自动识别第二个字母的顺序来进行排序,以此类推

逆序

既然有正着来,我们当然也可以反着来排序,不然sort()后面的括号拿来好看的吗,哈哈哈

我们这里只需要向sor()方法传递参数reverse=True即可

list_1 = ['one', 'two', 'three', 'four', 'five']
print(list_1)

list_1.sort(reverse=True)
print(list_1)

同样的,这样操作对列表也是永久性的

['one', 'two', 'three', 'four', 'five']
['two', 'three', 'one', 'four', 'five']

 

sorted()

当我们需要保留原列表的排序顺序时,可以使用sorted(),如:

list_1 = ['one', 'two', 'three', 'four', 'five']
print(list_1)

print(sorted(list_1))

print(list_1)

我们首先打印出这个列表,然后使用sorted()进行排序打印,然后再次打印这个列表

['one', 'two', 'three', 'four', 'five']
['five', 'four', 'one', 'three', 'two']
['one', 'two', 'three', 'four', 'five']

注意!!!这里原列表的顺序并没有改变

如果我们需要逆序打印,操作如sort()的逆序打印

 

reverse()

要反转,注意!!!是反转打印列表,我们则用reverse()

list_1 = ['one', 'two', 'three', 'four', 'five']
print(list_1)

list_1.reverse()
print(list_1)

注意,方法reverse()不是按字母顺序相反来排序,只是单纯的反转列表中的元素顺序

并且是永久性修改顺序,但是连续使用两次此函数就可以恢复原理啊的排列顺序

['one', 'two', 'three', 'four', 'five']
['five', 'four', 'three', 'two', 'one']

 

posted @ 2023-05-25 03:16  放氮气的蜗牛  阅读(36)  评论(0编辑  收藏  举报  来源