[英]How to reorder a python list backwards starting with the 0th element?
I'm trying to go through a list in reverse order, starting with the -0 indexed item (which is also the 0th item), rather than the -1 indexed item, so that I'll now have the new list to use. 我试图以相反的顺序浏览一个列表,从-0索引项(也是第0项)开始,而不是-1索引项,这样我现在就可以使用新列表了。 I've come up with two ways to do this, but neither seems both concise and clear. 我想出了两种方法来做到这一点,但似乎既不简洁又清晰。
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]
Is there a way in python 3 to use slicing or another method to achieve this more simply? 有没有一种方法在python 3中使用切片或其他方法来更简单地实现这一点?
If you are up for a programming golf: 如果您正在打高尔夫球:
>>> a_list = [1, 2, 3, 4, 5]
>>> [a_list[-i] for i in range(len(a_list))]
[1, 5, 4, 3, 2]
I think your first suggestion is the cleanest way of doing this. 我认为你的第一个建议是最干净的方法。 If you're really optimizing for character count, you can remove two characters from the first slice: 如果您真的在优化字符数,可以从第一个切片中删除两个字符:
print(a_list[:1] + a_list[:0:-1])
Shift everything left by one and reverse. 把所有东西都换成一个并反转。
my_list.append(my_list.pop(0))
print my_list[::-1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.