【问题标题】:Swapping first and last items in a list交换列表中的第一个和最后一个项目
【发布时间】:2013-11-09 02:42:25
【问题描述】:

如何交换给定列表中的数字?

例如:

list = [5,6,7,10,11,12]

我想将12 换成5

是否有内置的 Python 函数可以让我这样做?

【问题讨论】:

  • 什么指定要交换哪些元素?值(将每 12 替换为 5,将每 5 替换为 12)、位置(在第一个和最后一个位置切换值)或其他规则?例如,您希望 [5,5,12,12] 发生什么?
  • 我希望列表中的最后一个数字始终与列表中的第一个数字交换......在任何给定列表中。

标签: python list python-2.7 python-3.x swap


【解决方案1】:
>>> lis = [5,6,7,10,11,12]
>>> lis[0], lis[-1] = lis[-1], lis[0]
>>> lis
[12, 6, 7, 10, 11, 5]

上述表达式的Order of evaluation

expr3, expr4 = expr1, expr2

RHS 上的第一个项目被收集在一个元组中,然后 tuple is unpacked 并分配给 LHS 上的项目。

>>> lis = [5,6,7,10,11,12]
>>> tup = lis[-1], lis[0]
>>> tup
(12, 5)
>>> lis[0], lis[-1] = tup
>>> lis
[12, 6, 7, 10, 11, 5]

【讨论】:

  • 你好!感谢您的及时回复!您能否解释一下这段代码中发生了什么...我是编程新手。
  • @user2891763 我已经添加了一些解释。
  • 这种交换技术也适用于numpy.ndarray
【解决方案2】:

您可以使用此代码进行交换,

list[0],list[-1] = list[-1],list[0]

【讨论】:

  • 是的。 numpy.ndarray 也同样适用
【解决方案3】:

您可以使用“*”运算符。

my_list = [1,2,3,4,5,6,7,8,9]
a, *middle, b = my_list
my_new_list = [b, *middle, a]
my_list
[1, 2, 3, 4, 5, 6, 7, 8, 9]
my_new_list
[9, 2, 3, 4, 5, 6, 7, 8, 1]

阅读here了解更多信息。

【讨论】:

    【解决方案4】:

    使用要更改的数字的索引。

    In [38]: t = [5,6,7,10,11,12]
    
    In [40]: index5 = t.index(5) # grab the index of the first element that equals 5
    
    In [41]: index12 = t.index(12) # grab the index of the first element that equals 12
    
    In [42]: t[index5], t[index12] = 12, 5 # swap the values
    
    In [44]: t
    Out[44]: [12, 6, 7, 10, 11, 5]
    

    然后你可以做一个快速交换功能

    def swapNumbersInList( listOfNums, numA, numB ):
        indexA = listOfNums.index(numA)
        indexB = listOfNums.index(numB)
    
        listOfNums[indexA], listOfNums[indexB] = numB, numA
    
    # calling the function
    swapNumbersInList([5,6,7,10,11,12], 5, 12)
    

    【讨论】:

      【解决方案5】:

      另一种方式(不那么可爱):

      mylist   = [5, 6, 7, 10, 11, 12]
      first_el = mylist.pop(0)   # first_el = 5, mylist = [6, 7, 10, 11, 12]
      last_el  = mylist.pop(-1)  # last_el = 12, mylist = [6, 7, 10, 11]
      mylist.insert(0, last_el)  # mylist = [12, 6, 7, 10, 11]
      mylist.append(first_el)    # mylist = [12, 6, 7, 10, 11, 5]
      

      【讨论】:

        【解决方案6】:
        array = [5,2,3,6,1,12]
        temp = ''
        lastvalue = 5
        
        temp = array[0]
        array[0] = array[lastvalue]
        array[lastvalue] = temp
        
        print(array)
        

        希望这会有所帮助:)

        【讨论】:

          【解决方案7】:

          这对我来说终于奏效了。

          def swap(the_list):
              temp = the_list[0]
              the_list[0] = the_list[-1]
              the_list[-1] = temp
              return the_list
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2023-03-16
            • 2021-06-08
            • 2022-12-20
            • 2013-12-23
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多