Reverse a list without reversed command
本问题已经有最佳答案,请猛点这里访问。
我想在不使用
1 2 3 4 5 6 7 8 9 10 11 | list = [] x = 1 #Import 20 random numbers for i in range (0,20): list.append (x) print (list) for i in range (20,0,-1): # <-- I know, this is wrong. I used it as an example print (list[i]) |
解决方案:
1 2 3 4 5 6 7 8 9 10 11 | list = [] x = 1 #Import 20 random numbers for i in range (0,20): list.append (x) print (list) for i in range(len(list) - 1, -1, -1): print(list[i]) |
您可以简单地使用python的slice表示法向后单步执行列表:
1 | print(list[::-1]) |
演示:
1 2 3 4 | >>> lst = [1, 2, 3] >>> lst[::-1] [3, 2, 1] >>> |
事实上,如果你用
1 2 3 4 5 6 7 | >>> from timeit import timeit >>> lst = list(range(1000)) >>> timeit('list(reversed(lst))', 'from __main__ import lst') 18.91587534169846 >>> timeit('lst[::-1]', 'from __main__ import lst') 9.677450346342901 >>> |
而且打字也比较少。:)