python列表和字符串的三种逆序遍历方式

版权声明:本文为博主原创文章,未经博主允许不得转载。博客地址:http://blog.csdn.net/qq_22186119 https://blog.csdn.net/qq_22186119/article/details/79201205

python列表和字符串的三种逆序遍历方式

列表的逆序遍历

a = [1,3,6,8,9]
print("通过下标逆序遍历1:")
for i in a[::-1]:
    print(i, end=" ")
print("\n通过下标逆序遍历2:")
for i in range(len(a)-1,-1,-1):
    print(a[i], end=" ")
print("\n通过reversed逆序遍历:")
for i in reversed(a):
    print(i, end=" ")

输出

通过下标逆序遍历1:
9 8 6 3 1 
通过下标逆序遍历2:
9 8 6 3 1 
通过reversed逆序遍历:
9 8 6 3 1 

字符串的逆序遍历和列表一样。

猜你喜欢

转载自blog.csdn.net/qq_22186119/article/details/79201205