python入門—認識列表

來源:互聯網
上載者:User

標籤:class   ref   中括弧   結構   pop   app   style   title   lan   

本節內容:
1、查([])
2 、增(append,insert)
3、 改(重新賦值)
4 、刪(remove,del,pop)
5、 其他動作

 

什麼是列表:

列表(list)是Python以及其他語言中最常用到的資料結構之一。Python使用使用中括弧 [ ] 來解析列表。列表是可變的(mutable)——可以改變列表的內容。

 

對應操作:

1 、查([])
1 print(a[1:3])#取a的索引1到3的元素,並且不會取到索引3的元素2 print(a[1:])#取a的索引1到最後所有的元素3 print(a[1:-1])#取a的索引1到倒數第1個的所有元素(不包括第1個)4 print(a[1:-2])#取a的索引1到倒數第2個的所有元素(不包括第2個)5 print(a[1:-1:2])#隔一個取a的索引1到倒數第1個的所有元素(不包括第1個,2是步長)6 print(a[6::-2])#從右至左隔一個取a的索引6到左邊的所有元素(-2是隔一個從右至左取值)
 2 、增(append,insert)

insert 方法用於將對象插入到列表中,而append方法則用於在列表末尾追加新的對象

1 a.append(‘增加1‘)#預設插在最後的位置2 print(a)3 4 a.insert(1,‘增加2‘)#將資料插在任意的位置5 print(a)

 

3、 改(重新賦值)
1 a[1] = ‘修改1‘ #修改a索引1的元素2 print(a)3 a[1:4] = [‘a‘, ‘b‘, ‘c‘]  #修改a索引1到3的所有元素4 print(a)
 4 、刪(remove,del,pop)
 1 a.remove(‘2‘)  #刪除2的元素內容,remove只刪除內容(remove後面括弧裡為一個整體) 2 print(a) 3  4 a.pop(3)  #刪除a的索引3的元素,pop刪除會返回刪除的值 5 print(a) 6 a.pop()  #預設刪除最後一個 7 print(a) 8 b = a.pop(3)#pop刪除會返回刪除的值,我們可以對刪除的值進行一系列的操作 9 print(b)10 11 del a[2]  # del是列表之外的刪除,什麼都可以刪除12 print(a)13 del a14 print(a)15 16 a.clear()  #clear是清空17 print(a)

 

5、 其他動作

5.1  count

       count 方法統計某個元素在列表中出現的次數:

1 count 方法統計某個元素在列表中出現的次數2 a = [‘to‘, ‘a‘, ‘to‘, ‘a‘, ‘to ‘, ‘to‘]3 t = a.count(‘to‘)  #查詢to出現的次數4 print(t)

 

5.2 extend

         extend 方法可以在列表的末尾一次性追加另一個序列中的多個值:

1 extend 方法可以在列表的末尾一次性追加另一個序列中的多個值2 a = [‘1‘, ‘2‘, ‘3‘]3 b = [‘4‘, ‘5‘, ‘6‘]4 a.extend(b)  #把b列表添加到a列表5 print(a)

 

  extend 方法修改了被擴充的列表,而原始的串連操作(+)則不然,它會返回一個全新的列表:

 1 >>> a = [1, 2, 3]  2 >>> b = [4, 5, 6]  3 >>> a.extend(b)  4 >>> a  5 [1, 2, 3, 4, 5, 6]  6 >>>  7 >>> a + b  8 [1, 2, 3, 4, 5, 6, 4, 5, 6]  9 >>> a 10 [1, 2, 3, 4, 5, 6] 

 

5.3  index

       index 方法用於從列表中找出某個值第一個匹配項的索引位置: 

1 index 方法用於從列表中找出某個值第一個匹配項的索引位置2 a = [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘]3 b = a.index(‘c‘)  #取a列表中c元素的索引4 print(b)

 

5.4  reverse

       reverse 方法將列表中的元素反向存放:

1 reverse 方法將列表中的元素反向存放2 a = [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘]3 a.reverse()   #把a列表的元素反向存放4 print(a)

 

5.5  sort

       sort 方法用於在原位置對列表進行排序:

1 sort 方法用於在原位置對列表進行排序2 a = [‘a‘, ‘d‘, ‘e‘, ‘b‘, ‘c‘]3 b = [‘5‘, ‘4‘, ‘2‘, ‘3‘, ‘1‘, ‘6‘]4 a.sort()5 print(a)6 b.sort()7 print(b)

 

python入門—認識列表

相關文章

聯繫我們

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