简体   繁体   English

如何从第0个元素开始向后重新排序python列表?

[英]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.

相关问题 Python - 如何从不是第 0 个元素而是第 x 个元素循环数组? - Python - how to for loop an array from not 0th but xth element? 想要通过从第 0 个索引开始在其存在旁边插入每个元素直到满足条件来使列表等于目标长度 - Want to make a list equal to a target length by inserting every element next to its presence starting from 0th index until condition is satisfied python 用于在第一个元素没有第 0 个元素开始的循环 - python for loops being started at 1st element no 0th element 如何指定第0个参数以外的python参数 - How to specify python arguments except 0th argument 如何从第 0 个日期开始获得每 3 个日期 - How to get the every 3rd date starting from the 0th one Python - 将浮点数转换为 int 以用作数组索引返回数组的第 0 个元素 - Python - Casting a float as int to be used as array index returns 0th element of the array 如何有效地比较字典中列表中的项目与第二个字典中另一个列表中的第0个项目 - How to efficiently compare the items in a list within a dictionary to the 0th item within another list within a second dictionary 如何基于第0列中的字符串将嵌套列表(用作矩阵)细分为列表 - How to subdivide a nested list (used as a matrix) into lists based on the string in the 0th column python中如何删除未命名的索引行,将第0行替换为索引行进行数据分析 - How to delete Unnamed index row and replace 0th row as index row in python for data analysis 如何在Python 3中的列表中向后减去? - How to subtract backwards in a list in Python 3?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM