如何在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)时间。
其他回答
内置功能最少,假设是面试设置
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)
问题不是如何反向返回一个列表,而是如何使用示例列表名数组反向返回一个列表。
反转名为“array”的列表使用array.reverse()。
通过使用array[:] = array[::-1]将列表定义为对其本身的切片修改,还可以使用上面描述的非常有用的slice方法来反转列表。
使用切片,例如array = array[::-1],是一个简洁的技巧,非常python化,但对于新手来说可能有点晦涩。使用reverse()方法是进行日常编码的好方法,因为它易于阅读。
然而,如果你需要在面试问题中反转列表,你可能无法使用这些内置的方法。面试官会看你如何解决问题,而不是Python知识的深度,需要一个算法的方法。下面的例子,使用一个经典的交换,可能是一种方法:-
def reverse_in_place(lst): # Declare a function
size = len(lst) # Get the length of the sequence
hiindex = size - 1
its = size/2 # Number of iterations required
for i in xrange(0, its): # i is the low index pointer
temp = lst[hiindex] # Perform a classic swap
lst[hiindex] = lst[i]
lst[i] = temp
hiindex -= 1 # Decrement the high index pointer
print "Done!"
# Now test it!!
array = [2, 5, 8, 9, 12, 19, 25, 27, 32, 60, 65, 1, 7, 24, 124, 654]
print array # Print the original sequence
reverse_in_place(array) # Call the function passing the list
print array # Print reversed list
**The result:**
[2, 5, 8, 9, 12, 19, 25, 27, 32, 60, 65, 1, 7, 24, 124, 654]
Done!
[654, 124, 24, 7, 1, 65, 60, 32, 27, 25, 19, 12, 9, 8, 5, 2]
注意,这将不适用于元组或字符串序列,因为字符串和元组是不可变的,也就是说,您不能写入它们来更改元素。
使用一些逻辑
用一些老派的逻辑来练习面试。
从前到后交换数字。使用两个指针索引[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]
要反转相同的列表,请使用:
array.reverse()
将反向列表赋值到其他列表使用:
newArray = array[::-1]