python列表操作使用樣本分享

來源:互聯網
上載者:User
複製代碼 代碼如下:


Python 3.3.4 (v3.3.4:7ff62415e426, Feb 10 2014, 18:13:51) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> cast=["cleese","palin","jones","idle"]
>>> print(cast)
['cleese', 'palin', 'jones', 'idle']
>>> print(len(cast))#顯示資料項目數量
4
>>> print(cast[1])#顯示列表中第2個資料項目的值
palin
>>> cast.append("gilliam")#在列表末尾添加一個資料項目
>>> print(cast)
['cleese', 'palin', 'jones', 'idle', 'gilliam']
>>> cast.pop()#刪除列表末尾的資料項目
'gilliam'
>>> print(cast)
['cleese', 'palin', 'jones', 'idle']
>>> cast.extend(["gilliam","chapman"])#在列表末尾增加一個資料項目集合
>>> print(cast)
['cleese', 'palin', 'jones', 'idle', 'gilliam', 'chapman']
>>> cast.remove("chapman")#刪除指定的資料項目
>>> print(cast)
['cleese', 'palin', 'jones', 'idle', 'gilliam']
>>> cast.insert(0,"chapman")#在指定的位置增加資料項目
>>> print(cast)
['chapman', 'cleese', 'palin', 'jones', 'idle', 'gilliam']
>>>

下面是講定義一個def函數,isinstance()函數,for in,if else等的運用以及邏輯
複製代碼 代碼如下:


movies=["the holy grail",1975,"terry jone & terry gilliam",91,
["graham chapman",
["michael palin","john cleese","terry gilliam",
"eric idle","terry jones"]]]
def print_lol(the_list):#定義一種函數
for each_item in the_list:#for in迴圈迭代處理列表,從列表起始位置到末尾
if isinstance(each_item,list):#isinstance()檢測each_item裡每一項
#是不是list類型
print_lol(each_item)#如果是,調用函數print_lol
else:print(each_item)#如果不是,輸出這一項

print_lol(movies)#在movies列表中調用函數
"""
之前if else語句不對齊導致報錯
"""

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.