如何在Python中反向迭代列表?
请参见:如何获得列表的反向副本(避免在.reverse后链接方法时使用单独的语句)?
如何在Python中反向迭代列表?
请参见:如何获得列表的反向副本(避免在.reverse后链接方法时使用单独的语句)?
当前回答
使用反向(数组)可能是最好的方法。
>>> array = [1,2,3,4]
>>> for item in reversed(array):
>>> print item
如果你需要了解如何实现这个不使用内置反转。
def reverse(a):
midpoint = len(a)/2
for item in a[:midpoint]:
otherside = (len(a) - a.index(item)) - 1
temp = a[otherside]
a[otherside] = a[a.index(item)]
a[a.index(item)] = temp
return a
这需要O(N)时间。
其他回答
>>> l = [1, 2, 3, 4, 5]
>>> print(reduce(lambda acc, x: [x] + acc, l, []))
[5, 4, 3, 2, 1]
def reverse(text):
output = []
for i in range(len(text)-1, -1, -1):
output.append(text[i])
return output
use
print(list(reversed(list_name)))
使用一些逻辑
用一些老派的逻辑来练习面试。
从前到后交换数字。使用两个指针索引[0]和索引[last]
def reverse(array):
n = array
first = 0
last = len(array) - 1
while first < last:
holder = n[first]
n[first] = n[last]
n[last] = holder
first += 1
last -= 1
return n
input -> [-1 ,1, 2, 3, 4, 5, 6]
output -> [6, 5, 4, 3, 2, 1, -1]
使用列表。Reverse将列表就地反转:
>>> xs = [0, 10, 20, 40]
>>> xs.reverse()
>>> xs
[40, 20, 10, 0]
使用切片以相反的顺序创建一个新列表:
>>> xs[::-1]
[40, 20, 10, 0]