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

2022-09-18 11:38:53

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

列表的逆序遍历

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

输出

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

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

  • 作者:招财酷炫猫
  • 原文链接:https://blog.csdn.net/qq_22186119/article/details/79201205
    更新时间:2022-09-18 11:38:53