【问题标题】:Invert the list by exchanging the first and last element, the second and second last, and so on通过交换第一个和最后一个元素、第二个和倒数第二个元素来反转列表,依此类推
【发布时间】:2021-08-14 00:03:55
【问题描述】:

所以基本上任务是通过将第一个元素更改为最后一个元素,将第二个元素更改为倒数第二个等来反转 List... 这是我尝试过的,但最后什么也没发生。你有什么想法在这里不起作用或我应该尝试什么不同的方法?

list=[3,6,9,12,15,18,21,24,27,30]
y = 0
x = len(list)-1
while y <= x:
    for i in list:
        list[y],list[x]=list[x],list[y]
        y+=1
        x-=1
for i in list:
    print(i)

【问题讨论】:

  • 删除这个for i in list:

标签: python list indexing reverse


【解决方案1】:

所有其他解决方案都是不错的方法,但如果您特别 要求通过将第一个元素更改为最后一个元素等来编写反转列表的逻辑......这里,

y = 0
x = len(list)-1
while y < x:
    list[y],list[x]=list[x],list[y]
    y+=1
    x-=1
for i in list:
    print(i)

【讨论】:

  • 谢谢,这正是我想要的。
【解决方案2】:

你可以这样做:

def reverse(lst):
    # Iterate over the half of the indexes
    for i in range(len(lst) // 2):
        # Swap the i-th value with the i-th to last value
        lst[i], lst[len(lst)-1-i] = lst[len(lst)-1-i], lst[i]
        
lst = [1, 2, 3, 4, 5]
reverse(lst)
print(lst)    # Outputs [5, 4, 3, 2, 1]


lst = [1, 2, 3, 4]
reverse(lst)
print(lst)    # Outputs [4, 3, 2, 1]

【讨论】:

  • len(lst)-1-i 好拗口……可以用~i
  • @KellyBundy 我认为~i 对于初学者来说相当可怕,但它是一个不错的选择!
【解决方案3】:

你可以使用reverse()函数:

l = [3,6,9,12,15,18,21,24,27,30]
l.reverse()

【讨论】:

    【解决方案4】:

    你可以这样做:

    l=[3,6,9,12,15,18,21,24,27,30]
    new_l=l[::-1]
    

    【讨论】:

    • 首先感谢您的帮助。我认为这可能是反转该列表的最优雅方式,但我特别要求将第一个更改为最后一个,第二个更改为倒数第二个元素等。我认为这不是一个有效的解决方案。跨度>
    【解决方案5】:

    以下将颠倒列表的顺序:

    >>> l = [3,6,9,12,15,18,21,24,27,30]
    
    >>> l[::-1]
    Out[11]: [30, 27, 24, 21, 18, 15, 12, 9, 6, 3]
    

    【讨论】:

      【解决方案6】:

      您可以使用此代码:

      for i in sorted(list,reverse=True):
      print(i)
      

      【讨论】:

        猜你喜欢
        • 2021-04-03
        • 1970-01-01
        • 1970-01-01
        • 2022-11-16
        • 1970-01-01
        • 2022-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多