Python - 反向遍历序列(列表、字符串、元组等)的五种方式

1. reversed()

a = [1, 2, 3, 4]
for i in reversed(a):
    print(i)

2. range(len(a)-1, -1, -1)

a = [1, 2, 3, 4]
for i in range(len(a)-1, -1, -1):
    print(a[i])

3. range(len(a)) + ~操作符

~按位取反运算符:对数据的每个二进制位取反,即把1变为0,把0变为1 。~x 类似于 -x-1

a = [1, 2, 3, 4]
for i in range(len(a)):
    print(a[~i])

4. slice

a = [1, 2, 3, 4]
for i in a[::-1]:
    print(i)

5. length-i-1

a = [1, 2, 3, 4]

seq_length = len(a)
for i in range(seq_length):
    print(a[seq_length-i-1])
posted @ 2019-10-04 00:16  Rocin  阅读(9314)  评论(0编辑  收藏  举报