簡體   English   中英

如何從第0個元素開始向后重新排序python列表?

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM