如何在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
其他回答
def reverse(my_list):
L = len(my_list)
for i in range(L/2):
my_list[i], my_list[L-i - 1] = my_list[L-i-1], my_list[i]
return my_list
问题不是如何反向返回一个列表,而是如何使用示例列表名数组反向返回一个列表。
反转名为“array”的列表使用array.reverse()。
通过使用array[:] = array[::-1]将列表定义为对其本身的切片修改,还可以使用上面描述的非常有用的slice方法来反转列表。
如果你想在其他变量中存储反转列表的元素,那么你可以使用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
使用一些逻辑
用一些老派的逻辑来练习面试。
从前到后交换数字。使用两个指针索引[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]
我在一次面试的python代码测试中遇到了这个问题。 以下是我的答案。 注意它适用于任何值任何长度
def get_reverse(list_check, count_num):
final_list =[]
for index in range(list_length):
value = list_check[count_num]
final_list.append(value)
count_num = count_num -1
return final_list
new_list = ['A', 'GOAT', 'C', 'D', 'Mac']
list_length = len(new_list)
x = list_length -1
print(get_reverse(new_list, x))