python列表(Lists)

來源:互聯網
上載者:User

標籤:python   list   lists   列表   

(1)Python擁有大量的複合資料類型,用於把其他值組合在一起。用途最廣的是列表,可以寫成方括弧之間的逗號分隔 值(項目iterms)的列表。列表中可能包含不同類型的項目(items),但所有的項目(items)通常具有相同的類型。

>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

(2)像字串(和所有內建的序列類型)一樣,列表可以使用索引和切片。

>>> squares[0]  # 返回一個值(項目)
1
>>> squares[-1]
25
>>> squares[-3:]  #返回一個新的列表
[9, 16, 25]

(3)列表同時也支援串連。

>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

(4)不同於不能改變的字串,列表是可以改變的,例如可以改變列表中的內容

>>> cubes = [1, 8, 27, 65, 125]  # 這裡的值有一些錯誤,因為這是一個立方表
>>> 4 ** 3  #4的立方是64,不是65
64
>>> cubes[3] = 64  # 替換錯誤的值
>>> cubes
[1, 8, 27, 64, 125]

可以通過append()方法,在列表結尾處添加新值。

>>> cubes.append(216)  # add the cube of 6
>>> cubes.append(7 ** 3)  # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]

賦值切片內容也是可行的,這可能會改變列表的大小,甚至清空列表。

>>> letters = [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘]
>>> letters
[‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘]
>>> #替換一些值
>>> letters[2:5] = [‘C‘, ‘D‘, ‘E‘]
>>> letters
[‘a‘, ‘b‘, ‘C‘, ‘D‘, ‘E‘, ‘f‘, ‘g‘]
>>> # 移除一些值
>>> letters[2:5] = []
>>> letters
[‘a‘, ‘b‘, ‘f‘, ‘g‘]
>>> # 清空列表
>>> letters[:] = []
>>> letters
[]
(5)內建函數len()也可以用來表示列表的大小。
>>> letters = [‘a‘, ‘b‘, ‘c‘, ‘d‘]
>>> len(letters)
4
(6)可以建立嵌套列表。
>>> a = [‘a‘, ‘b‘, ‘c‘]
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[[‘a‘, ‘b‘, ‘c‘], [1, 2, 3]]
>>> x[0]
[‘a‘, ‘b‘, ‘c‘]
>>> x[0][1]
‘b‘


python列表(Lists)

聯繫我們

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