如何在Python中反向迭代列表?
请参见:如何获得列表的反向副本(避免在.reverse后链接方法时使用单独的语句)?
如何在Python中反向迭代列表?
请参见:如何获得列表的反向副本(避免在.reverse后链接方法时使用单独的语句)?
当前回答
我发现(与其他一些建议相反)l.reverse()是迄今为止在Python 3和2中反转长列表的最快方法。我很想知道其他人是否可以复制这些时间。
L[::-1]可能更慢,因为它在反转列表之前复制了列表。在reversed(l)所做的迭代器周围添加list()调用必须增加一些开销。当然,如果你想要一个列表或迭代器的副本,那么就使用它们各自的方法,但如果你只想反转列表,那么l.reverse()似乎是最快的方法。
功能
def rev_list1(l):
return l[::-1]
def rev_list2(l):
return list(reversed(l))
def rev_list3(l):
l.reverse()
return l
List
l = list(range(1000000))
Python 3.5计时
timeit(lambda: rev_list1(l), number=1000)
# 6.48
timeit(lambda: rev_list2(l), number=1000)
# 7.13
timeit(lambda: rev_list3(l), number=1000)
# 0.44
Python 2.7计时
timeit(lambda: rev_list1(l), number=1000)
# 6.76
timeit(lambda: rev_list2(l), number=1000)
# 9.18
timeit(lambda: rev_list3(l), number=1000)
# 0.46
其他回答
使用切片,例如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]
注意,这将不适用于元组或字符串序列,因为字符串和元组是不可变的,也就是说,您不能写入它们来更改元素。
for x in array[::-1]:
do stuff
如果你想在其他变量中存储反转列表的元素,那么你可以使用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
另一个解决方案是使用numpy。翻一下
import numpy as np
array = [0, 10, 20, 40]
list(np.flip(array))
[40, 20, 10, 0]
这个类使用Python魔法方法和迭代器进行反转,并反转列表:
class Reverse(object):
""" Builds a reverse method using magic methods """
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def __next__(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
REV_INSTANCE = Reverse([0, 10, 20, 40])
iter(REV_INSTANCE)
rev_list = []
for i in REV_INSTANCE:
rev_list.append(i)
print(rev_list)
输出
[40, 20, 10, 0]