元組的使用與列表相似,不同之處在于元組是不可修改的,元組使用圓括號,而列表使用中括號
一、定義元組
1.使用逗號的方法
a = 1,2,3 #這樣就定義號一個元組了
print(type(a))
#結(jié)果顯示
<class 'tuple'>
2.使用圓括號的方法
a = (1,2,3)
print(type(a))
#結(jié)果顯示
<class 'tuple'>
3.使用tuple函數(shù)
alist = [1,2,3]
atuple = tuple(alist)
print(type(atuple))
#結(jié)果顯示
<class 'tuple'>
4.定義只有一個元素的元組
a = 1,
b = (1,)
print(type(a))
print(type(b))
#結(jié)果顯示
<class 'tuple'>
<class 'tuple'>
二、元組常用操作
1.下標(biāo)操作
atuple = ('a','b','c')
a = atuple[0]
print(a)
#結(jié)果顯示
a
2.切片操作:跟列表和字符串的切片操作一樣
3.解組操作
atuple = ('feiniu002',18)
name,age = atuple
print(name)
print(age)
#結(jié)果顯示
feiniu002
18
atuple = ('feiniu002',18,'廈門')
name,age,_ = atuple
print(name)
print(age)
#結(jié)果顯示
feiniu002
18
4.count方法:獲取元組中某個值出現(xiàn)的次數(shù),跟列表中的用法相同
5.index方法:獲取元組中某個值得下標(biāo),跟列表中的用法相同
三、元組存在的意義或應(yīng)用場景
1.元組在字典中可以當(dāng)做key來使用,而列表是不可以的。
a_tuple = ('username',)
a_dict = {a_tuple:'feiniu002'}
print(a_dict)
#結(jié)果顯示
{('username',): 'feiniu002'}
2.在函數(shù)中,有時候要返回多個值,一般采用元組的方式。
def person():
name = 'feiniu002'
age = 18
return name,age
a_tuple = person()
print(a_tuple)
#結(jié)果顯示
('feiniu002', 18)