python的元祖,集合,字典的常見函數
- 2020 年 1 月 19 日
- 筆記
# 關於元祖的函數
- 以下程式碼
- 以下函數,對 list 基本適用
關於元祖的函數¶
- 以下程式碼
In [2]:
# len :獲取元祖的長度
t = (1,2,3,4,5,6)
len(t)
Out[2]:
6
. . .
In [3]:
# 如果,列表或元祖中有多個最大值和多個最小值,則實際列印出哪個??
# max min :最大值最小值
# 如果,列表或元祖中有多個最大值和多個最小值,則實際列印出哪個??
print(max(t))
print(min(t))
6 1
. . .
In [5]:
t
xxxxxxxxxx
# tuple 轉化成或創建元祖
l = [1,2,3,4,5,6]
t = tuple(l)
print(t)
t = tuple()
print(t)
(1, 2, 3, 4, 5, 6) ()
. . .
# 元祖的函數
- 基本跟 list 通用
Type Markdown and LaTeX: α2α2
In [8]:
最前面的
# count :計算制定數據出現的次數
t = (1,2,3,4,5,6,55,3,55,3)
print(t)
# index : 求制定元素在元祖中的索引位置
print(t.index(55))
# 如果需要查找的數字是多個,則返回最前面的一個
print(t.index(3))
(1, 2, 3, 4, 5, 6, 55, 3, 55, 3) 6 2
. . .
In [12]:
* 20
xxxxxxxxxx
# 元祖變數交換法
a = 1
b = 3
print(a)
print(b)
print("*" * 20)
# java程式設計師會這樣寫
c = a
a = b
b = c
print(a)
print(b)
print("*" * 20)
# python 寫法
a,b = b,a
print(a)
print(b)
1 3 ******************** 3 1 ******************** 1 3
. . .
xxxxxxxxxx
# 集合- set
- 集合是高中數學的一個概念
- 一堆確定的無序的唯一的數據,集合中每一個數據成為一個元素
Type Markdown and LaTeX: α2α2
In [16]:
s
xxxxxxxxxx
# 集合定義
s = set()
print(type(s))
print(s)
# 此時大括弧里一定要有值,否則定義出的是 dict
s = {1,2,3,4,5,6}
print(s)
<class 'set'> set() {1, 2, 3, 4, 5, 6}
. . .
In [14]:
# 如果只是用大括弧定義,則定義的是一個 dict 類型
d = {}
print(type(d))
print(d)
<class 'dict'> {}
. . .
# 集合的特徵
- 集合是無序的,即無法使用索引分片
- 集合內數據元素具有唯一性,可以用來排除重複數據
- 集合內的數據, str int float tuple 冰凍集合等,即內部只能放置可哈希數據
Type Markdown and LaTeX: α2α2
# 集合序列操作
Type Markdown and LaTeX: α2α2
In [17]:
"woshishui","wozaina","wozaizuoshenm"
x
# 成員檢測
# in not in
s = {4,5,"woshishui","wozaina","wozaizuoshenm"}
print(s)
if "woshishui" in s:
print("大大")
if "woshini" not in s:
print("你是誰")
{4, 5, 'wozaizuoshenm', 'woshishui', 'wozaina'} 大大 你是誰
. . .
便利操作
xxxxxxxxxx
# 集合便利操作
Type Markdown and LaTeX: α2α2
In [18]:
xxxxxxxxxx
# for 循環
s = {4,5,"woshishui","wozaina","wozaizuoshenm"}
for i in s:
print(i,end=" ")
4 5 wozaizuoshenm woshishui wozaina
. . .
In [20]:
# 帶有元組的集合遍歷
s = {(4,5,6),("woshishui","wozaina","wozaizuoshenm"),(5,6,7)}
for k,n,m in s:
print(k,"--",n,"--",m)
5 -- 6 -- 7 4 -- 5 -- 6 woshishui -- wozaina -- wozaizuoshenm
. . .
# 集合的內置函數
xxxxxxxxxx
# 集合的內置函數
Type Markdown and LaTeX: α2α2
In [22]:
ss
xxxxxxxxxx
# 普通集合
# 以下集合在初始化後自動過濾掉重複元素
s = {2,22,333,55,66,33,11,559,66,1,2,3,45,6,12,3,2}
print(s)
# 普通的集合內置函數
ss = {i for i in s}
print(ss)
{33, 2, 66, 1, 3, 6, 11, 12, 333, 45, 559, 22, 55} {33, 2, 3, 66, 1, 6, 11, 12, 333, 45, 559, 22, 55}
. . .
In [23]:
sss
xxxxxxxxxx
# 帶條件的集合內置函數
sss = {i for i in s if i % 2 == 0 }
print(sss)
{2, 66, 6, 12, 22}
. . .
In [29]:
if n ==4
# 多循環的集合內置函數
s1 = {1,2,3,4,5}
s2 = {"W","shishui","N"}
s = {m*n for m in s2 for n in s1}
print(s)
s = {m*n for m in s2 for n in s1 if n ==4}
print(s)
{'NNN', 'shishuishishuishishui', 'NNNNN', 'WW', 'NNNN', 'N', 'W', 'WWWW', 'shishui', 'shishuishishui', 'shishuishishuishishuishishuishishui', 'WWWWW', 'WWW', 'NN', 'shishuishishuishishuishishui'} {'shishuishishuishishuishishui', 'WWWW', 'NNNN'}
. . .
# 集合函數/關於集合的函數
Type Markdown and LaTeX: α2α2
In [30]:
# 集合內元素的最小值
# len, max, min, :跟其他基本函數一致
s = {589,654,321,123,258}
print(len(s))# 集合長度
print(max(s))# 集合內元素的最大值
print(min(s))# 集合內元素的最小值
5 654 123
. . .
In [32]:
l = [1,2,3] s = set(l) print(s)
x
# set :生成一個集合
l = [1,2,3]
s = set(l)
print(s)
{1, 2, 3}
. . .
In [33]:
,生成新的集合
# add : 向集合內添加元素,生成新的集合
s = {2,3,4}
s.add(546)
print(s)
{2, 3, 4, 546}
. . .
In [34]:
s
xxxxxxxxxx
l = [1,2,3]
print(s)
print(id(s))
s = set(l)
print(s)
print(id(s))
{2, 3, 4, 546} 2286297091432 {1, 2, 3} 2286297091656
. . .
In [36]:
成新的集合
# clear:原集合序列清空,不生成新的集合
l = [1,2,3]
print(s)
print(id(s))
s.clear()
print(s)
print(id(s))
set() 2286297091656 set() 2286297091656
. . .
In [37]:
# copy : 拷貝
# remove: 移除指定的值,直接改變原有值(不生成新的集合序列),如果要刪除的值不錯在,則報錯
# discard :移除集合內指定的值,跟 remove 一樣,但是如果要刪除的數據不存在話,不報錯
s = {1,2,3,4,5,6}
s.remove(5)
print(s)
s.discard(1)
print(s)
print("*" * 20)
s.discard(1100)
print(t)
s.remove(1100)
print(s)
# 為什麼 remove 刪除不存在的值會報 KeyError
{1, 2, 3, 4, 6} {2, 3, 4, 6} ******************** (1, 2, 3, 4, 5, 6, 55, 3, 55, 3)
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-37-dfd60878c871> in <module>() 12 print(t) 13 ---> 14 s.remove(1100) 15 print(s) KeyError: 1100
. . .
In [39]:
# pop 隨機移除一個元素
s = {1,2,3,4,5,6}
d = s.pop()
print(d)
print(s)
1 {2, 3, 4, 5, 6}
. . .
In [40]:
# 集合函數
# intersection:交集
# difference:差集
# union:並集
# issubset:檢測一個元素是否為另一個元素的子集
# issuperset:檢查一個元素是否為另一個元素的超集
s1 = {1,2,3,4,5,6,7}
s2 = {9,10,11,12,15,16}
s_1 = s1.intersection(s2)
print(s_1)
s_2 = s1.difference(s2)
print(s_2)
s_3 = s1.issubset(s2)
print(s_3)
set() {1, 2, 3, 4, 5, 6, 7} False
. . .
In [44]:
# 集合數學操作
s1 = {}
s2 = {}
s_1 = s1 - s2
print(s_1)
s_2 = s1 + s2
print(s_2)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-44-758adeea170a> in <module>() 3 s2 = {} 4 ----> 5 s_1 = s1 - s2 6 print(s_1) 7 TypeError: unsupported operand type(s) for -: 'dict' and 'dict'
. . .
# frozenset :冰凍集合
- 冰凍集合就是不可進行任何修改的集合
- frozenset 是一種特殊集合
frozenset :冰凍集合¶
- 冰凍集合就是不可進行任何修改的集合
- frozenset 是一種特殊集合
In [45]:
# 創建
s = frozenset()
print(type(s))
print(s)
<class 'frozenset'> frozenset()
. . .
# dict 字典
- 字典是一種組合數據,沒有順序的組合數據,建議鍵值對形式出現
dict 字典¶
- 字典是一種組合數據,沒有順序的組合數據,建議鍵值對形式出現
In [56]:
# 字典的創建
# 創建空字典
d = {}
print(d)
# 創建空字典2
d = dict()
print(d)
# 創建有值的字典,每一組數據用冒號隔開,每一對鍵值用逗號隔開
d = {"one":1, "tow":2,"whree":3}
print(d)
# 用 dict 創建有內容的字典1
d = dict({"one":1, "tow":2,"whree":3})
print(d)
# 用 dict 創建有內容的字典2
# 利用關鍵字參數
d = dict(one=1, tow=2,whree=3)
print(d)
d = dict ([("tow",2),("three",3),("five",5)])
print(d)
{} {} {'one': 1, 'tow': 2, 'whree': 3} {'one': 1, 'tow': 2, 'whree': 3} {'one': 1, 'tow': 2, 'whree': 3} {'tow': 2, 'three': 3, 'five': 5}
. . .
任何值
xxxxxxxxxx
# 字典的特徵
- 字典是序列類型,但是是無序序列,所以沒有分片和索引
- 字典中的數據每個都是鍵值對組成,即 k T 對
- key :必須是可哈希的值,比如 int, string, float, tple,但是 list, set, dict 不可以
- value: 任何值
Type Markdown and LaTeX: α2α2
xxxxxxxxxx
# 字典常見操作
Type Markdown and LaTeX: α2α2
In [59]:
d
xxxxxxxxxx
# 訪問數據
d = {"one":1,"tow":2,"three":3}
# 注意訪問格式
# 中括弧內是鍵值
print(d["one"])
d["one"] = "eins"
print(d)
# 刪除某個操作
# 使用 del 操作
del d["one"]
print(d)
1 {'one': 'eins', 'tow': 2, 'three': 3} {'tow': 2, 'three': 3}
. . .
In [62]:
# 成員檢測,檢測的是key 內容
# 成員檢測, in, not in
# 成員檢測,檢測的是key 內容
d = {"one":1,"tow":2,"three":3}
if 2 in d:
print("value")
if "tow" in d:
print("key")
if ("tow",2) in d:
print("kv")
key
. . .
In [66]:
注意以下特殊用法
# 便利在 python2 和python3 中區別較大,程式碼不通用
# 按 key 來使用 for 循環
d = {"one":1,"tow":2,"three":3}
# 使用 for 循環,直接按 key 值訪問
for k in d:
print(k, d[k])
# 上述程式碼可以改寫成如下程式碼
for k in d.keys():
print(k, d[k])
# 只訪問字典的值
for v in d.values():
print(v)
# 注意以下特殊用法
for k,v in d:
print(k,"--",v)
one 1 tow 2 three 3 one 1 tow 2 three 3 1 2 3
. . .
xxxxxxxxxx
# 字典生成式
字典生成式¶
In [71]:
d = {"one":1,"two":2,"three":3}
x
d = {"one":1,"two":2,"three":3}
# 常規字典生成式
dd = {k:v for k,v in d.items()}
print(dd)
# 加限制條件的字典生成式
dd = {k:v for k,v in d.items() if v % 2 ==0}
print(dd)
{'one': 1, 'two': 2, 'three': 3} {'two': 2}
. . .
# 字典相關函數
字典相關函數¶
In [73]:
d = {"one":1,"two":2,"three":3}
x
# 通用函數:len, max, min, dict
# *str (字典):返回字典的字元串格式
d = {"one":1,"two":2,"three":3}
print(str(d))
{'one': 1, 'two': 2, 'three': 3}
. . .
In [75]:
it
# clear: 清空字典
# items:返回字典的鍵值對 組成的元祖格式
d = {"one":1,"two":2,"three":3}
i = d.items()
print(type(i))
print(i)
<class 'dict_items'> dict_items([('one', 1), ('two', 2), ('three', 3)])
. . .
In [77]:
k = d.keys() print(type(k)) print(k)
x
# keys : 返回字典的鍵值組成的一個結構
k = d.keys()
print(type(k))
print(k)
<class 'dict_keys'> dict_keys(['one', 'two', 'three'])
. . .
In [78]:
values
# values: 同理 ,返回一個可迭代的結構
k = d.values()
print(type(k))
print(k)
<class 'dict_values'> dict_values([1, 2, 3])
. . .
In [80]:
,300
x
# get : 根據指定鍵返回相應的值,好處式,可以設默認值
d = {"one":1,"two":2,"three":3}
print(d.get("on333"))
# get 默認值是 None,可以設置
print(d.get("one",200))
print(d.get("on333",300))
# 體會以下程式碼跟上面的程式碼的區別
print(d["on333"])
None 1 300
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-80-d0b504524683> in <module>() 7 print(d.get("on333",300)) 8 # 體會以下程式碼跟上面的程式碼的區別 ----> 9 print(d["on333"]) KeyError: 'on333'
. . .
In [81]:
d
xxxxxxxxxx
# fromkeys:使用指定的序列作為鍵,使用一個值作為字典的所有的鍵的值
l = ["eins","zwei","drei"]
# 注意 fromkeys 兩個參數的類型
# 注意 fromkeys 的調用主體
d = dict.fromkeys(l,"heheheh")
print(d)
{'eins': 'heheheh', 'zwei': 'heheheh', 'drei': 'heheheh'}