python in three ways reverse list

1, the reversed built-in function ()

li =[1, 2, 3, 4, 5, 6]
a = list(reversed(li))
print (a)

Note: reversed () function returns an iterator instead of a List, you need to change if the function list

2, built-in function sorted ()

sorted () syntax

sorted(iterable[, cmp[, key[, reverse]]])

Parameter Description:

  • iterable - iterables.
  • cmp - compare function, the two parameters, parameter values ​​are taken from the subject may be iterative, this function must comply with the rules is greater than 1 is returned, it is less than -1, is equal to 0 is returned.
  • key - is mainly used for the comparison element, only one parameter, the specific parameter is a function of iteration may be taken from the object, specify one of the elements in the iteration to be sorted.
  • reverse - collation, reverse = True descending, reverse = False ascending (default).

The return value
is returned to reorder the list.

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:××× 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
a=[1,2,3,4,5,6,7,8,9] 
c=sorted(a, reverse=True) 
print (c)

Note: sorted () in descending order, no effect for the content is not reversed order, for improvement here.

3: Using fragment

a=[1,2,3,4,5,6,7,8,9] 
d=a[::-1] 
print (d)  

Note: wherein [:: --1] Representative values ​​from back to front, each step value 1

Guess you like

Origin blog.51cto.com/14246112/2448590