python學習三:列表,元組,python學習列表

來源:互聯網
上載者:User

python學習三:列表,元組,python學習列表
1.列表:1.列表的定義方式:

list1 = [1,2,3,4,"hello","world"]

如上所示,list1就是一個列表,列表的內容以中括弧包含起來

print(list1[2])

取值方式是使用下表的方式,下表從0開始,取第編號為2的下標,取出來的值為3

2.列表的常用操作:
list1.append(5) #追加一個元素

如果想要追加多個元素,我們可以append一個list2,如下

list2 = [3,9,5,9,8,7,6]list1.append(list2)for i in  list1:    print(i)print(list1)輸出:1234
hello
world[3, 9, 5, 9, 8, 7, 6][1, 2, 3, 4,'hello', 'world',[3, 9, 5, 9, 8, 7, 6]]

從上邊的例子我們可以知道,列表是可以有重複元素的,並且可以在一個列表中追加另一個列表,但是有一點要注意,就算追加了另一個列表,在list1中也是將那個追加的列表當作一個元素來看待,而不是將list2中的每個元素追加到list1中。

list1.clear(); #清空當前列表print(list1)

輸出:
[]
print(list1.count("hello")) #計算出當前元素出現的次數,列印結果1
list2 = list1.copy() #複製一個列表,需要注意的是與便便直接賦值的區別,如果我們改變了list1,那麼list3也會變,也就是說list1與list3是同一個記憶體位址,而list2是一個新的記憶體位址,不會受到list1改變的影響list3 = list1print(list2)print(list3)
list2 = ["cat","dog"]#用於添加另一個列表,append無法解決的問題使用extend即可list1.extend(list2) print(list1)輸出:[1, 2, 3, 4, 'hello', 'world', 'cat', 'dog']
print(list1.index("hello")) #擷取當前元素所在下表,從0開始,列印結果為4
list1.insert(0,"a") #插入一個元素,第一個參數為下表,第二個參數是要插入的內容print(list1)

輸出:
['a', 1, 2, 3, 4, 'hello', 'world']
print(list1.pop(4)) #用於移除i列表中的一個元素,並且返回移除元素的值print(list1)
list1.remove(4) #移除元素,參數為要移除的參數的值list1.remove("hello")print(list1)輸出[1, 2, 3, 'world']
list1.reverse() #列表的反響排序print(list1)輸出:['world', 'hello', 4, 3, 2, 1]
 2.元組1.元組的定義方式
tuple2 = ("hello","world",2,8)

與列表非常像,區別就是列表用的中括弧[]包含元素,而元組用的是小括弧。

還有一種定義方式是由列錶轉化而來,如下:

tuple2 = tuple(list1)

列印下tuple2出現的就是list1的所有元素,不過是由小括弧()包起來的。

元組與列表最大的區別就是元組是不能改變內容的,一旦一個元組被定義,那麼直到該元組被回收,都不能改變這個元組的值。

聯繫我們

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