Beginning Python From Novice to Professional (3) - 列表操作,pythonnovice

來源:互聯網
上載者:User

Beginning Python From Novice to Professional (3) - 列表操作,pythonnovice

列表操作

list函數:

>>> list('hello')['h', 'e', 'l', 'l', 'o']
改變列表:

>>> x=[1,1,1]>>> x[1]=2>>> x[1, 2, 1]
刪除元素:

>>> names = ['wu','li','zhao','qian']>>> del names[1]>>> names['wu', 'zhao', 'qian']
分區賦值:

>>> name = list('perl')>>> name['p', 'e', 'r', 'l']>>> name[2:] = list('ar')>>> name['p', 'e', 'a', 'r']
>>> num = [1,2,3,4,5]>>> num[1:4]=[] #從1位開始但不包括4位>>> num[1, 5]
append 列表末尾添加新元素:

>>> lst = [1,2,3]>>> lst.append(4)>>> lst[1, 2, 3, 4]
count 統計元素的個數:

>>> ['we','have','we','a','dog'].count('we')2
extend 擴充列表:

>>> a = [1,2,3]>>> b = [4,5,6]>>> a.extend(b)>>> a[1, 2, 3, 4, 5, 6]
index 找出第一個匹配項的位置:

>>> sentence = ['I','have','a','little','dog']>>> sentence.index('little')3
insert 將對象插入列表:

>>> num = [1,2,3,5,6,7]>>> num.insert(3,'four')>>> num[1, 2, 3, 'four', 5, 6, 7]
pop 移除列表元素,預設最後一個:

>>> x = [1,2,3]>>> x.pop()3>>> x[1, 2]>>> x.pop(0)1>>> x[2]
結合append:

>>> x = [1,2,3]>>> x.append(x.pop())>>> x[1, 2, 3]
remove 移除列表中的第一個匹配項:

>>> x = ['to','be','or','not','to','be']>>> x.remove('be')>>> x['to', 'or', 'not', 'to', 'be']
reverse 反向存放元素:

>>> x = [1,2,3]>>> x.reverse()>>> x[3, 2, 1]
sort 排序:

>>> x = [4,6,2,1,7,9]>>> x.sort()>>> x[1, 2, 4, 6, 7, 9]
>>> x.sort(reverse=True)>>> x[9, 7, 6, 4, 2, 1]>>> x.sort(reverse=False)>>> x[1, 2, 4, 6, 7, 9]

聯繫我們

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