我试图以相反的顺序遍历一个列表,从-0索引项(也是第0个项)开始,而不是-1索引项,以便现在有了新的列表供使用。我想出了两种方法来做到这一点,但似乎都不是简洁明了的。
a_list = [1, 2, 3, 4, 5]
print(a_list[:1] + a_list[:0:-1]) # take two slices of the list and add them
# [1, 5, 4, 3, 2]
list_range = range(-len(a_list)+1,1)[::-1] # create an appropriate new index range mapping
print([a_list[i] for i in list_range]) # list comprehension on the new range mapping
# [1, 5, 4, 3, 2]
Run Code Online (Sandbox Code Playgroud)
python 3中有没有一种方法可以使用切片或另一种方法来更简单地实现这一目的?
如果您准备参加编程高尔夫:
>>> a_list = [1, 2, 3, 4, 5]
>>> [a_list[-i] for i in range(len(a_list))]
[1, 5, 4, 3, 2]
Run Code Online (Sandbox Code Playgroud)