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. 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
缺点是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])