Python中元組的使用

2021-10-19 05:36:01 字數 1690 閱讀 5211

2 命名元組

注意:元組只有乙個元素時一定要加逗號,例如b=(1),b的型別為int

a=()

##空元組b=(

1)c=(

1,)d=

(1,'mm',[

2,3]

)print

(a,type

(a))

##()

print

(b,type

(b))

##1

print

(c,type

(c))

##(1,)

print

(d,type

(d))

##(1, 'mm', [2, 3])

a=(2

,7)b=

(1,2

)print

(a+b)

##(2, 7, 1, 2)

print

(a*3

)##(2, 7, 2, 7, 2, 7)

a=(2

,'a',[

1,'s',4]

,7)print

(a[:2]

)##(2, 'a')前兩個元素

print

(a[::-

1])##(7, [1, 's', 4], 'a', 2)倒序

print

(a[3:]

)##(7,)前三個不輸出

a=(1

,'a',[

1,'s',4]

,1)print

(a.count(1)

)## 2

print

(a.index(1)

)## 0

print

(a.count(2)

)## 0

print

(a.index(2)

)## 報錯

資料一旦儲存為元組後,訪問其中的內容只能通過下標索引的方式去訪問,資料一旦多了通過記住每個下標那就會顯得相當困難,元組不能為元組內部的資料進行命名,而 collections.namedtuple 可以來構造乙個含有欄位名稱的元組類,命名元組可以通過逗號+欄位名來獲取元素值

# 從collections模組中匯入namedtuple工具

from collections import namedtuple

# 建立命名元組物件user

user=namedtuple(

'user',(

'name'

,'age'

,'city'))

# 給命名元組傳值

user1=user(

'tom',12

,'鄭州'

)# 列印命名元組

print

(user1)

print

(user1.name)

print

(user1.age)

print

(user1.city)

輸出:user(name=

'tom'

, age=

12, city=

'鄭州'

)tom

12鄭州

python中元組的使用

我的學習筆記 markdown真的是乙個很好用的電子筆記,以前總習慣手寫筆記,費時費力,也不好展現。接觸到csdn這個格式後,又了解了一下markdown這個排版美觀的輸出形式,真的是大愛。我自用的是typora,據了解還有其他的。重點是可以直接上傳我的學習筆記到csdn超級方便。因為想學習演算法類...

python中元組的簡介

t 1,2.3,true,star print t print type t 執行結果為 1,2.3,true,star t1 1,2,3 4 print t1 執行結果為 1,2,3,4 4 t2 hello print type t2 執行結果為 allowusers root westos r...

Python中元組的函式

定義乙個帶欄位名的元組 from collections import namedtuple user namedtuple user name age user user lisi male 12 print user user name lisi male age 12 fields 元組的屬性...