python学习笔记:翻转列表list

方法一:逆序index

a = [ 2, 3, 5, 7 ]
print("And here are the items in reverse:")
for index in range(len(a)):
    revIndex = len(a)-1-index
    print("a[", revIndex, "] =", a[revIndex])

   输出:7\n5\n3\n2\n

方法二:使用函数reversed(a)

    注意:此处list a不发生改变,返回反转的迭代器。

               此外,a也可以为string、tuple、range。

a = [ 2, 3, 5, 7 ]
print("And here are the items in reverse:")
for item in reversed(a):
    print(item)
print(a)            

   输出:7\n5\n3\n2\n    a不变为[2,3,5,7]

方法三:使用函数a.reverse()

   注意:与reversed(a)的区别!!此处返回反转后的list a,即 a发生改变。

              仅能作用于一维数组list,string、tuple无此函数。

a = [ 2, 3, 5, 7 ]
print("And here are the items in reverse:")
a.reverse()
for item in a:
    print(item)
print(a)

   输出:7\n5\n\3\n\2\n   a改变为[2,3,5,7]

猜你喜欢

转载自blog.csdn.net/xiaozhimonica/article/details/85692152