天天看點

042 元組類型内置方法

目錄

一、元組類型内置方法(tuple)1.1 優先掌握(*****)

二、元組和清單的差別

一、元組類型内置方法(tuple)

元組是不可變的清單,即元組的值不可更改,是以元組一般隻用于隻存不取的需求。也是以元組可以被清單取代掉,是以元組相比較清單使用的很少。元組相比較清單的優點為:清單的值修改後,清單的結構将會發生改變,而元組隻需要存儲,是以清單在某種程度上而言需要占用更多的記憶體。但是目前工業上記憶體已經不是問題了,是以工業上元組一般不會使用。

1.用途:多個裝備、多個愛好、多門課程,甚至是多個女朋友

2.定義:在()内可以有多個任意類型的值,逗号分隔元素

<code>print(f"my_girl_friend: {my_girl_friend}")</code>

3.常用操作+内置方法:常用操作和内置方法:

索引取值

切片(顧頭不顧尾,步長)

長度len

成員運算in和not in

循環

count

index

1.索引取值

<code>print(f"name_tuple[0]: {name_tuple[0]}")</code>

2.切片(顧頭不顧尾,步長)

<code>print(f"name_tuple[1:3:2]: {name_tuple[1:3:2]}")</code>

3.長度

<code>print(f"len(name_tuple): {len(name_tuple)}")</code>

4.成員運算

<code>print(f"'nick' in name_tuple: {'nick' in name_tuple}")</code>

5.循環

<code>for name in name_tuple: print(name)</code>

6.count()

<code>print(f"name_tuple.count('nick'): {name_tuple.count('nick')}")</code>

7.index()

<code>print(f"name_tuple.index('nick'): {name_tuple.index('nick')}")</code>

4.存一個值or多個值:多個值

5.有序or無序:有序

6.可變or不可變:不可變資料類型

清單可變的原因是:索引所對應的值的記憶體位址是可以改變的

元組不可變得原因是:索引所對應的值的記憶體位址是不可以改變的,或者反過來說,隻要索引對應值的記憶體位址沒有改變,那麼元組是始終沒有改變的。

<code>print(f"id(t1[0]): {id(t1[0])}") print(f"id(t1[1]): {id(t1[1])}") print(f"id(t1[2]): {id(t1[2])}")</code>

<code></code>

<code>t1[0][0] = 'A' print(f"t1[0][0]: {t1[0][0]}") print(f"id(t1[0]): {id(t1[0])}") print(f"t1: {t1}")</code>

繼續閱讀