如何在Python中反向迭代列表?
请参见:如何获得列表的反向副本(避免在.reverse后链接方法时使用单独的语句)?
如何在Python中反向迭代列表?
请参见:如何获得列表的反向副本(避免在.reverse后链接方法时使用单独的语句)?
当前回答
通过切换相反索引的引用来就地反转:
>>> l = [1,2,3,4,5,6,7]
>>> for i in range(len(l)//2):
... l[i], l[-1-i] = l[-1-i], l[i]
...
>>> l
[7, 6, 5, 4, 3, 2, 1]
其他回答
内置功能最少,假设是面试设置
array = [1, 2, 3, 4, 5, 6,7, 8]
inverse = [] #create container for inverse array
length = len(array) #to iterate later, returns 8
counter = length - 1 #because the 8th element is on position 7 (as python starts from 0)
for i in range(length):
inverse.append(array[counter])
counter -= 1
print(inverse)
>>> L = [1, 2, 3, 4]
>>> L = [L[-i] for i in range(1, len(L) + 1)]
>>> L
[4, 3, 2, 1]
要获得一个新的反向列表,应用reversed函数并将项目收集到一个列表中:
>>> xs = [0, 10, 20, 40]
>>> list(reversed(xs))
[40, 20, 10, 0]
在列表中向后迭代:
>>> xs = [0, 10, 20, 40]
>>> for x in reversed(xs):
... print(x)
40
20
10
0
>>> xs = [0, 10, 20, 40]
>>> xs[::-1]
[40, 20, 10, 0]
这里将解释扩展片语法。请参见文档。
如果你想在其他变量中存储反转列表的元素,那么你可以使用revArray = array[::-1]或revArray = list(reversed(array))。
但是第一个变体稍微快一点:
z = range(1000000)
startTimeTic = time.time()
y = z[::-1]
print("Time: %s s" % (time.time() - startTimeTic))
f = range(1000000)
startTimeTic = time.time()
g = list(reversed(f))
print("Time: %s s" % (time.time() - startTimeTic))
输出:
Time: 0.00489711761475 s
Time: 0.00609302520752 s