一、元組類型內置方法(tuple)
元組是不可變的列表,即元組的值不可更改,因此元組一般只用於只存不取的需求。也因此元組可以被列表取代掉,所以元組相比較列表使用的很少。元組相比較列表的優點為:列表的值修改后,列表的結構將會發生改變,而元組只需要存儲,因此列表在某種程度上而言需要占用更多的內存。但是目前工業上內存已經不是問題了,所以工業上元組一般不會使用。
1.用途:多個裝備、多個愛好、多門課程,甚至是多個女朋友
2.定義:在()內可以有多個任意類型的值,逗號分隔元素
# my_girl_friend = tuple(('jason','tank','sean'))
my_girl_friend = ('jason', 'tank', 'sean')
print(f"my_girl_friend: {my_girl_friend}")
my_girl_friend: ('jason', 'tank', 'sean')
name_str = ('egon') # ()只是普通包含的意思
name_tuple = ('egon',)
print(f"type(name_str): {type(name_str)}")
print(f"type(name_tuple): {type(name_tuple)}")
type(name_str): <class 'str'>
type(name_tuple): <class 'tuple'>
3.常用操作+內置方法:常用操作和內置方法:
1.1 優先掌握(*****)
-
索引取值
-
切片(顧頭不顧尾,步長)
-
長度len
-
成員運算in和not in
-
循環
-
count
-
index
1.索引取值
# tuple之索引取值
name_tuple = ('nick', 'jason', 'tank', 'sean')
# name_tuple[0] = 'nick handsom' # 報錯
print(f"name_tuple[0]: {name_tuple[0]}")
name_tuple[0]: nick
2.切片(顧頭不顧尾,步長)
# tuple之切片
name_tuple = ('nick', 'jason', 'tank', 'sean')
print(f"name_tuple[1:3:2]: {name_tuple[1:3:2]}")
name_tuple[1:3:2]: ('jason',)
3.長度
# tuple之長度
name_tuple = ('nick', 'jason', 'tank', 'sean')
print(f"len(name_tuple): {len(name_tuple)}")
len(name_tuple): 4
4.成員運算
# tuple之成員運算
name_tuple = ('nick', 'jason', 'tank', 'sean')
print(f"'nick' in name_tuple: {'nick' in name_tuple}")
'nick' in name_tuple: True
5.循環
# tuple之循環
name_tuple = ('nick', 'jason', 'tank', 'sean')
for name in name_tuple:
print(name)
nick
jason
tank
sean
6.count()
# tuple之count()
name_tuple = ('nick', 'jason', 'tank', 'sean')
print(f"name_tuple.count('nick'): {name_tuple.count('nick')}")
name_tuple.count('nick'): 1
7.index()
# tuple之index()
name_tuple = ('nick', 'jason', 'tank', 'sean')
print(f"name_tuple.index('nick'): {name_tuple.index('nick')}")
name_tuple.index('nick'): 0
4.存一個值or多個值:多個值
5.有序or無序:有序
name_tuple = ('nick',)
print(f'first:{id(name_tuple)}')
first:4394454152
6.可變or不可變:不可變數據類型
二、元組和列表的區別
l = ['a', 'b', 'c']
print(f"id(l[0]): {id(l[0])}")
l[0] = 'A'
print(f"id(l[0]): {id(l[0])}")
id(l[0]): 4357367208
id(l[0]): 4357775176
列表可變的原因是:索引所對應的值的內存地址是可以改變的
元組不可變得原因是:索引所對應的值的內存地址是不可以改變的,或者反過來說,只要索引對應值的內存地址沒有改變,那么元組是始終沒有改變的。
t1 = (['a', 'b', 'c'], 'wc', 'office')
print(f"id(t1[0]): {id(t1[0])}")
print(f"id(t1[1]): {id(t1[1])}")
print(f"id(t1[2]): {id(t1[2])}")
t1[0][0] = 'A'
print(f"t1[0][0]: {t1[0][0]}")
print(f"id(t1[0]): {id(t1[0])}")
print(f"t1: {t1}")
id(t1[0]): 4394709960
id(t1[1]): 4374626968
id(t1[2]): 4394453568
t1[0][0]: A
id(t1[0]): 4394709960
t1: (['A', 'b', 'c'], 'wc', 'office')