狼先生

列表中元素的排序

描述:

  • 对列表进行排序

方法:

对列表进行排序

  • list.sort() # 对列表按字母顺序永久排序

例子:

>>> name = ['a','d','c','b']
>>> name.sort()
>>> name
['a', 'b', 'c', 'd']

>>> print(name)
['a', 'b', 'c', 'd']
  • list.sort(reverse = True) #对列表按字母顺序,反序永久排序

例子:

>>> name = ['a','d','c','b']
>>> name.sort(reverse = True)
['d', 'c', 'b', 'a']

>>> print(name)
['d', 'c', 'b', 'a']
  • sorted(list) # 对列表按字母顺序临时排序

例子:

>>> name = ['a','d','c','b']
>>> sorted(name)
['a', 'b', 'c', 'd']

>>> print(name)
['a', 'd', 'c', 'b']
  • sorted(list, reverse = True) # 对列表按字母顺序,反序临时排序

例子:

>>> name = ['a','d','c','b']
>>> sorted(name, reverse = True)
['d', 'c', 'b', 'a']

>>> print(name)
['a', 'd', 'c', 'b']
  • list.reverse() #将列表进行反转

例子:

>>> name = ['a','d','c','b']
>>> name.reverse()
['b', 'c', 'd', 'a']

# 再次调用reverse,恢复到原来的排列顺序
>>> name.reverse()
['a', 'd', 'c', 'b']
Copyright © 2020 Mr.Wolf Views