[英]Python - how to for loop an array from not 0th but xth element?
[英]How to reorder a python list backwards starting with the 0th element?
我试图以相反的顺序浏览一个列表,从-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 = [1, 2, 3, 4, 5]
>>> [a_list[-i] for i in range(len(a_list))]
[1, 5, 4, 3, 2]
我认为你的第一个建议是最干净的方法。 如果您真的在优化字符数,可以从第一个切片中删除两个字符:
print(a_list[:1] + a_list[:0:-1])
把所有东西都换成一个并反转。
my_list.append(my_list.pop(0))
print my_list[::-1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.