Python針對給定列表中元素進行翻轉操作的方法分析

來源:互聯網
上載者:User
這篇文章主要介紹了Python針對給定列表中元素進行翻轉操作的方法,結合執行個體形式分析了Python針對列表元素基於切片及遍曆輸出兩種翻轉操作實現技巧,具有一定參考借鑒價值,需要的朋友可以參考下

本文執行個體講述了Python針對給定列表中元素進行翻轉操作的方法。分享給大家供大家參考,具體如下:

題目

給定一列表,翻轉其中的元素,倒序輸出

做法很簡單,這裡給出來兩種做法,第一種最簡單使用的是針對列表的切片操作,下面是具體實現


#!usr/bin/env python#encoding:utf-8'''''__Author__:沂水寒城功能:翻轉列表'''def inverse_list1(num_list):  '''''  翻轉列表  '''  print num_list[::-1]def inverse_list2(num_list):  '''''  翻轉列表  '''  n = len(num_list)  for i in xrange(n / 2):    t = num_list[i]    num_list[i] = num_list[n-1-i]    num_list[n-1-i] = t  print num_listif __name__ == '__main__':  print "指令碼之家測試結果:"  num_list=[1,2,3,4,5,6,7,8,9,0]  inverse_list1(num_list)  inverse_list2(num_list)


結果如下:

指令碼之家測試結果:
[0, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[0, 9, 8, 7, 6, 5, 4, 3, 2, 1]

運行結果如下:

從上述樣本對比中可見基於切片的操作是最簡單的翻轉方法。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.