Python入門教程 元組 字典 集合

2021-08-22 08:30:49 字數 2229 閱讀 8816

元組

不可變的列表,不可變物件可以優化

tup = ()

tup = (1)

tup is 1

>>>true

tup = (1)

tup>>>1

tup = (1,)

tup>>>(1,)

type(tup)

>>>tuple

tup = (1001,1003,"test")

tup[1]

>>>1003

tup[1] = 1992

tup[1]

>>>報錯

元祖賦值問題

tup = (1,2,[3,4])

tup[2] +=[5,6]

tup>>>(1,2,[3,4,5,6])

##元祖不可修改,但是裡面的列表則可以修改,記憶體位址不變

元祖不可刪除 但是可以組合(index切片)

(1,2)+(3,4)

>>>(1,2,3,4)

tup = (1,2,'a',1)

tup.index(1)

>>>0

tup.index(1,2)

>>>3

tup.index(1,1,4)

>>>3

tup.count(1)

>>>2

##獲取數量

##(1)為元素為1的索引,(1,2)1的元素從第2個索引開始,(1,1,4)1的元素從第1個索引開始到第4個索引。返回第乙個符合值的索引位置

##相當於切片 tup[1:4]?

price_map =
dct = {}

dct[1] = "a"

dct["a"] = 1

dct>>>

dct.get('a')

>>>1

dct['b']

>>>報錯

dct.get('b',2)

##如果沒有就返回2

dct["a"]=4

dct.update(a=1,b=2,c=3)

dct>>>dct

"a" in dct

>>>true

del dct["a"]

列表用索引訪問,字典用鍵訪問,列表有順序,字典沒順序

dct.key()

>>>dict_keys(['a','c'])

dct.values()

>>>dict_values([1,2])

dct.item()

dict_items([("a",1),("c",2)])

集合

>>>

#集合沒有重複 有序嗎?

set([1,3,2,1])

>>>

list()

>>>[1,2,3]

##執行一次列表操作

s = set()

s>>>set()

s.add(1)

s>>>

s.update([2,3])

s>>>

s.update([3,4])

s>>>

s.remove(4)

>>>

s.remove(4)

s>>>報錯

s.discard(4)

>>>不報錯

##集合無序

issubset/issuperset 判斷超集和子集關係

set([1]).issubset(set([1,2]))

>>>true

set([1]).issuperset(set([1,2]))

>>>false

set([1,2]).issuperset(set([1]))

>>>true

##交集 並集 補集

s1 = set([1,2,3])

s2 = set([3,4,1])

s1&s2

>>>

s1 | s2

>>>

s1-s2

>>>

s2-s1

>>>

元組擴充套件閱讀

1. 2.

字典擴充套件閱讀

1. l#collections.ordereddict

2. files

集合擴充套件閱讀

1.

Python入門教程 元組

一 語法 elem1,elem2.元組與列表類似,不同之處在於 1 元組的元素不能修改。2 元組使用小括號,而列表使用方括號。可以建立乙個空的元組 tup 注意 元組中只包含乙個元素時,需要在元素後面新增逗號。tup 50,print hi 4 hihihihi print hi 4 hi hi h...

python入門教程少兒 Python 入門教程

python 入門教程 python是一種解釋型 物件導向 動態資料型別的高階程式語言。python由guido van rossum於1989年底發明,第乙個公開發行版發行於1991年。像perl語言一樣,python 源 同樣遵循 gpl gnu general public license 協...

Python基礎入門教程

python基礎教程 python 簡介 python環境搭建 python 基礎語法 python 變數型別 python 運算子 python 條件語句 python 迴圈語句 python while迴圈語句 python for 迴圈語句 python 迴圈巢狀 python break 語...