pyhton中实现列表元素顺序颠倒
1、循环
>>> test1 = ["aa","bb","cc","dd","ee","ff","gg"]
>>> test1
['aa', 'bb', 'cc', 'dd', 'ee', 'ff', 'gg']
>>> test2 = []
>>> test2
[]
>>> for i in range(-1,-(len(test1)+1),-1):
test2.append(test1[i])
>>> test2
['gg', 'ff', 'ee', 'dd', 'cc', 'bb', 'aa']
2、列表分片
>>> test1[::1] ['aa', 'bb', 'cc', 'dd', 'ee', 'ff', 'gg', 'hh', 'ii', 'jj'] >>> test1[::-1] ['jj', 'ii', 'hh', 'gg', 'ff', 'ee', 'dd', 'cc', 'bb', 'aa']
3、就地反转
>>> test1 = ["aaa","bbb","ccc","ddd"]
>>> test1
['aaa', 'bbb', 'ccc', 'ddd']
>>> test2 = test1[:]
>>> test2
['aaa', 'bbb', 'ccc', 'ddd']
>>> test1.reverse()
>>> test1
['ddd', 'ccc', 'bbb', 'aaa']
>>> test2[::-1]
['ddd', 'ccc', 'bbb', 'aaa']
>>> test2
['aaa', 'bbb', 'ccc', 'ddd']