python 列表排序

发布时间:2022-05-12 09:46:50 人气:173 作者:多测师

  使用列表对象的sort()方法进行原地排序,支持多种不同的排序方法。

  >>> aList = [3, 4, 5, 6, 7, 9, 11, 13, 15, 17]

  >>> import random

  >>> random.shuffle(aList)

  >>> aList

  [3, 4, 15, 11, 9, 17, 13, 6, 7, 5]

  >>> aList.sort() #默认是升序排序

  >>> aList.sort(reverse = True) #降序排序

  >>> aList

  [17, 15, 13, 11, 9, 7, 6, 5, 4, 3]

  >>> aList.sort(key = lambda x:len(str(x))) #按转换成字符串的长度排序

  >>> aList

  [9, 7, 6, 5, 4, 3, 17, 15, 13, 11]

python 列表排序

  使用内置函数sorted()对列表进行排序并返回新列表

  >>> aList

  [9, 7, 6, 5, 4, 3, 17, 15, 13, 11]

  >>> sorted(aList) #升序排序

  [3, 4, 5, 6, 7, 9, 11, 13, 15, 17]

  >>> sorted(aList,reverse = True) #降序排序

  [17, 15, 13, 11, 9, 7, 6, 5, 4, 3]

  使用列表对象的reverse()方法将元素原地逆序

  >>> aList = [3, 4, 5, 6, 7, 9, 11, 13, 15, 17]

  >>> aList.reverse()

  >>> aList

  [17, 15, 13, 11, 9, 7, 6, 5, 4, 3]

  使用内置函数reversed()对列表元素进行逆序排列并返回迭代对象

  >>> aList = [3, 4, 5, 6, 7, 9, 11, 13, 15, 17]

  >>> newList = reversed(aList) #返回reversed对象

  >>> list(newList) #把reversed对象转换成列表

  [17, 15, 13, 11, 9, 7, 6, 5, 4, 3]

  >>> for i in newList:

  print(i, end=' ') #这里没有输出内容

  #迭代对象已遍历结束

  >>> newList = reversed(aList) #重新创建reversed对象

  >>> for i in newList:

  print(i, end=' ')

  17 15 13 11 9 7 6 5 4 3

  以上内容为大家介绍了python 列表排序,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注多测师。https://www.e70w.com/xwzx/


返回列表
在线客服
联系方式

热线电话

17727591462

上班时间

周一到周五

二维码
线