我试图以相反的顺序遍历列表,从-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]
有没有办法在Python 3中使用切片或其他方法更简单地实现这个?
a_list[0] == a_list[-0]
@a_list[0]等于@a_list[-0] - user11563547a_list[::-1]
。 - Sociopath