【问题标题】:How to reverse a list while preserving the last index?如何在保留最后一个索引的同时反转列表?
【发布时间】:2019-07-24 19:25:17
【问题描述】:

如何反转列表中除最后一个索引之外的所有项目?

例子:

aList = ['1', '2', 'STAY']

我希望结果是:

aList = ['2', '1', 'STAY']

【问题讨论】:

  • 你试过什么?您具体需要哪些帮助?
  • aList = aList[:-1][::-1] + [aList[-1]]

标签: python list indexing reverse except


【解决方案1】:

切片非常简单:

aList = ['1', '2', '3', '4', 'STAY']
aList[:-1] = aList[-2::-1]
print(aList)

输出:

['4', '3', '2', '1', 'STAY']

解释:

aList[:-1] = aList[-2::-1]
       ^            ^   ^
       |            |   |___Travel towards the beginning
       |            |
       |      Start from the second to last element
       |
Assign from first to second to last element

【讨论】:

  • 您的解释可能被解释为aList[-2::-1] == aList[-2:][::-1],事实并非如此。该步骤的符号决定了-2: 部分的意思是“从索引0 开始直到倒数第二个元素”还是“从倒数第二个元素开始直到列表末尾”。
  • @GiacomoAlzetta 稍微编辑了一下,现在你觉得更清楚了吗?
【解决方案2】:

您可以执行以下操作:

alist=['1','2','STAY']  # Your List
fix=alist[-1] # Declaring the last element in alist using negative index
del alist[-1] # Deleting last element
alist.reverse() # Reversing the remaining list
alist.append(fix) # Inserting the last element in alist

打印列表以获得所需的列表。

【讨论】:

    猜你喜欢
    • 2020-02-10
    • 1970-01-01
    • 2016-01-02
    • 2019-10-31
    • 2022-12-04
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 2011-12-14
    相关资源
    最近更新 更多