开发者社区> 问答> 正文

Python 将列表中的头尾两个元素对调

Python 将列表中的头尾两个元素对调

展开
收起
游客ejnn55cgkof5g 2020-02-14 18:02:57 892 0
1 条回答
写回答
取消 提交回答
  • def swapList(newList): 
        size = len(newList) 
          
        temp = newList[0] 
        newList[0] = newList[size - 1] 
        newList[size - 1] = temp 
          
        return newList 
    
    newList = [1, 2, 3] 
      
    print(swapList(newList)) 
    以上实例输出结果为:
    
    [3, 2, 1]
    实例 2
    def swapList(newList): 
          
        newList[0], newList[-1] = newList[-1], newList[0] 
      
        return newList 
          
    newList = [1, 2, 3] 
    print(swapList(newList)) 
    以上实例输出结果为:
    
    [3, 2, 1]
    实例 3
    def swapList(list): 
          
        get = list[-1], list[0] 
          
        list[0], list[-1] = get 
          
        return list
          
    newList = [1, 2, 3] 
    print(swapList(newList)) 
    以上实例输出结果为:
    
    [3, 2, 1]
    2020-02-14 18:03:16
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载