python 中的list&tuple

來源:互聯網
上載者:User

標籤:pen   assm   app   元組   位置   div   不能   pos   ack   

list

Python內建的一種資料類型是列表:list
>>> classmates = [‘Michael‘, ‘Bob‘, ‘Tracy‘]
>>> classmates
[‘Michael‘, ‘Bob‘, ‘Tracy‘]
變數classmates就是一個list。用len()函數可以獲得list元素的個數:

>>> len(classmates)
3
索引來訪問list中每一個位置的元素,記得索引是從0開始的:

>>> classmates[0]
‘Michael‘

用-1做索引,直接擷取最後一個元素:

>>> classmates[-1]
‘Tracy‘
往list中追加元素到末尾:

>>> classmates.append(‘Adam‘)
>>> classmates
[‘Michael‘, ‘Bob‘, ‘Tracy‘, ‘Adam‘]

把元素插入到指定的位置,比如索引號為1的位置:

>>> classmates.insert(1, ‘Jack‘)
>>> classmates
[‘Michael‘, ‘Jack‘, ‘Bob‘, ‘Tracy‘, ‘Adam‘]

刪除list末尾的元素,用pop()方法:

>>> classmates.pop()
‘Adam‘
>>> classmates
[‘Michael‘, ‘Jack‘, ‘Bob‘, ‘Tracy‘]
刪除指定位置的元素,用pop(i)方法,其中i是索引位置:

>>> classmates.pop(1)
‘Jack‘
>>> classmates
[‘Michael‘, ‘Bob‘, ‘Tracy‘]

把某個元素替換成別的元素,可以直接賦值給對應的索引位置:

>>> classmates[1] = ‘Sarah‘

tuple

另一種有序列表叫元組:tuple
tuple一旦初始化就不能修改
當你定義一個tuple時,在定義的時候,tuple的元素就必須被確定下來
只有1個元素的tuple定義時必須加一個逗號,,來消除歧義:

>>> t = (1,)

python 中的list&tuple

聯繫我們

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