python基礎1--列表,python1--列表

來源:互聯網
上載者:User

python基礎1--列表,python1--列表

列表

列表是最常用的資料類型之一,通過列表可以對資料實現最方便的儲存、修改等操作

1.定義列表

1 fruits = ['apple','banana','orange']

2.通過下標訪問列表中的元素,下標從0開始計數

1 >>> fruits[0]2 'apple'3 >>> fruits[2]4 'orange'5 >>> fruits[-1]6 'orange'7 >>> fruits[-2]8 'banana'

3.切片

 1 >>> fruits = ['apple','banana','orange','peal','grape'] 2 >>> fruits[1:4]    #取下標1到下標4之間的數,包括1但不包括4 3 ['banana', 'orange', 'peal'] 4 >>> fruits[1:-1]   #取下標1至-1之間的數,不包括-1 5 ['banana', 'orange', 'peal'] 6 >>> fruits[0:3]    #從頭開始取,不包括3 7 ['apple', 'banana', 'orange'] 8 >>> fruits[:3]     #和上句一樣 9 ['apple', 'banana', 'orange']10 >>> fruits[3:]     #從下標3到最後,到末尾只能這樣取11 ['peal', 'grape']12 >>> fruits[0::2]   #從頭開始,步長為2,即隔一個取一個13 ['apple', 'orange', 'grape']14 >>> fruits[::2]    #和上句一iy15 ['apple', 'orange', 'grape']

4.追加,append()

1 >>> fruits2 ['apple', 'banana', 'orange', 'peal', 'grape']3 >>> fruits.append('newpeach')4 >>> fruits5 ['apple', 'banana', 'orange', 'peal', 'grape', 'newpeach']

5.插入元素

在下標1處插入一個西瓜(watermelon)

1 ['apple', 'banana', 'orange', 'peal', 'grape', 'newpeach']2 >>> fruits.insert(1,'watermelon')3 >>> fruits4 ['apple', 'watermelon', 'banana', 'orange', 'peal', 'grape', 'newpeach']

 

聯繫我們

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