开发者社区> 问答> 正文

Python 将列表中的指定位置的两个元素对调

Python 将列表中的指定位置的两个元素对调

展开
收起
游客ejnn55cgkof5g 2020-02-14 18:04:10 1163 0
1 条回答
写回答
取消 提交回答
  •       
        list[pos1], list[pos2] = list[pos2], list[pos1] 
        return list
      
    List = [23, 65, 19, 90] 
    pos1, pos2  = 1, 3
      
    print(swapPositions(List, pos1-1, pos2-1)) 
    以上实例输出结果为:
    
    [19, 65, 23, 90]
    实例 2
    def swapPositions(list, pos1, pos2): 
          
        first_ele = list.pop(pos1)    
        second_ele = list.pop(pos2-1) 
         
        list.insert(pos1, second_ele)   
        list.insert(pos2, first_ele)   
          
        return list
      
    List = [23, 65, 19, 90] 
    pos1, pos2  = 1, 3
      
    print(swapPositions(List, pos1-1, pos2-1)) 
    以上实例输出结果为:
    
    [19, 65, 23, 90]
    实例 3
    def swapPositions(list, pos1, pos2): 
      
        get = list[pos1], list[pos2] 
           
        list[pos2], list[pos1] = get 
           
        return list
      
    List = [23, 65, 19, 90] 
      
    pos1, pos2  = 1, 3
    print(swapPositions(List, pos1-1, pos2-1)) 
    以上实例输出结果为:
    
    [19, 65, 23, 90]
    2020-02-14 18:06:40
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

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