Python基礎 8 元組

2021-09-27 01:54:28 字數 2698 閱讀 1151

目錄

一、元組的定義

元組(tuple):帶了緊箍咒的列表

注意:定義元組時,如果只有乙個元素,元素後面一定要加逗號, 否則資料型別不確定

二、元組的常用方法

三、元組的特性(索引、切片、連線、重複、成員操作符、for迴圈)

四、元組的應用場景

1、不用第三個變數即可交換兩個變數的值:

2、列印變數

五、元組與列表型別轉換

不可變資料型別,沒有增刪改,可以儲存任意資料型別。

定義乙個元組

>>> t=(1,2,3,false,'hello')

>>> print(t,type(t))

((1, 2, 3, false, 'hello'), )

定義乙個空元組

>>> t=()

>>> print(type(t))

雖說,元組的內容不可以修改,但是如果元組裡面包含可變的資料型別,可以間接的去修改元組內容

>>> t1=([1,2,3],4,5)

>>> print(t1,type(t1))

(([1, 2, 3], 4, 5), )

>>> print(t1)

([1, 2, 3, 'hello'], 4, 5)

>>> a=(1)

>>> print(type(a))

>>> a=(1,)

>>> print(type(a))

返回索引號,計算元素出現的次數

>>> t=(1,2,"hello")

>>> t2=('hello')

>>> print(t.index(t2)) #返回t2第一次在t**現的索引號

2>>> print(t.count('hello') #計算hello出現的次數

1

t=(1,2,'hello','hello')

索引

>>> print(t[0])

1

切片

>>> print(t[::-1])    #倒序輸出

('hello', 'hello', 2, 1)

>>> print(t[:2]) #輸出前兩個

(1, 2)

>>> print(t[:-1]) #輸出除了最後乙個元素

(1, 2, 'hello')

連線

print(t + (1,2,3,4))

注意:不同的資料型別之前 不能連線

>>> print(t+('hello','world'))

(1, 2, 3, 4, 'hello', 'world')

>>> print(t+[123,421])

traceback (most recent call last):

file "", line 1, in typeerror: can only concatenate tuple (not "list") to tuple

重複

print(t * 20)

for迴圈

for i in t:

print(i)

成員操作符

print(1 in t)

print(1 not in t )

1、打包和解包

將若干個值全部賦給乙個變數,就會將這些值打包成乙個元組

將乙個元組賦值給若干個變數,就會按照順序將元組元素賦給若干個變數。

#打包

a = 1,2,3,4

print(type(a),a)

#輸出# (1, 2, 3, 4)

#解包i,j,k,f = a

print(i,j,k,f)

#輸出# 1 2 3 4

2、

a = 1

b = 2

a,b=b,a

實現原理:b,a =(1,2) b=(1,2)[0] a=(1,2)[1]

name='yyz'

age=20

t=(name,age)

print("名字:%s,年齡:%d" %t)

用元組,就不用再用以前的方法

print("名字:%s,年齡:%d" %(name,age))

3、

t2 = tuple(t1)  #直接將列表t1轉換為元組,並賦給變數t2

t3 = list(t2) #直接將元組t2轉換為列表,並賦值給t3

Python基礎 8 元組

元組與列表類似,不同之處在於元組的元素不能修改,元組用 定義,索引從0開始 注 元組中只包含乙個元素時,需要在元素後面新增 info tuple zhangsan 18,1.75 定義空元組 empty tuple 定義只包含乙個元素的元組 single tuple 5,取值和取索引,取索引就是已經...

python 初探8 元組

temp 1 temp 1 type temp temp2 1,2,3,4,5 temp2 1,2,3,4,5 type temp2 temp type temp temp type temp temp 1,temp 1,type temp python中的元素值是不允許刪除的,但我們可以使用 de...

Python基礎 05 元組

元組建立很簡單,只需要在括號中新增元素,並使用逗號隔開即可。如下例項 tup1 google runoob 1997,2000 tup2 1,2,3,4,5 tup3 a b c d 建立空元組 tup1 元組中只包含乙個元素時,需要在元素後面新增逗號,否則括號會被當作運算子使用 tup1 50 t...