【Python基礎】2萬字-詳解Python基礎函數,包教包會

2021-10-16 23:00:02

👉跳轉文末👈 獲取作者聯絡方式,共同學習進步

執行環境

python:3.8.3
jupyter-notebook : 6.4.0

注意:本文案例可以直接在 jupyter-notebook 上執行,但在 PyCharm 上的話需要程式碼的最後一句加上 print 哦!



輸入輸出函數

print()

print() 無疑是我們使用最多的函數,他可以直接輸出、指定間隔/結尾字元、將輸出內容儲存到指定檔案(應用:記錄自動化指令碼異常資訊)等。下面列舉它的常見用法。
1️⃣ 直接輸出

print('hello world')
output:hello world

2️⃣ 指定間隔字元sep

print('A', 'B', 'C', sep=' Python ')
output:A Python B Python C

3️⃣ 指定結尾字元

print('hello', 'world', end='Python')
output:hello worldPython

4️⃣ 將輸出內容儲存到outfile.txt檔案中

print('hello', 'world', sep=' ', file=open('outfile.txt', 'w', encoding='utf-8'))

input()

input() 可以接收使用者輸入的內容,並以字串的形式儲存。

name = input('name:')

在這裡插入圖片描述
jupyter notebook 上執行的效果可能和別的編輯器不同,但操作都是輸入完後,按 「回車」 即可。



獲取資料型別

type()

type() 返回指定值的資料型別。

type([1, 2])
output:list

isintance()

isintance() 判斷傳入的值是否為指定型別,返回 True/False

isinstance('Python新視野', str)
output:True


字串操作

str()

str() 將指定值轉為字串型別。

str(1.23)
output:‘1.23’

eval()

eval() 將字串轉成有效的表示式來求值或者計算結果。可以將字串轉化成列表(list),元組(tuple),字典(dict),集合(set)等。

res = eval("{'name': 'Python'}")
type(res)
output:dict

str.capitalize()

capitalize() 返回字串中的首字母大寫,其餘小寫的字串

cap_str = 'python新視野'.capitalize()
cap_str
output:‘Python新視野’

str.center()

center() 返回一個指定寬度的居中字串,左右部分空餘部分用指定字元填充。

  • width:長度
  • fillchar:空餘部分填充的字元,預設使用空格
center_str = 'Python新視野'.center(15, "!")
center_str
output:’!!!Python新視野!!!’

str.count()

str.count(sub, start, end) 返回 substr 中出現的次數,可以通過 [start, end] 指定範圍,若不指定,則預設查詢整個字串。

  • sub: 子串
  • start: 開始的索引,預設為 0
  • end: 結束的索引,預設為字串的長度
name = 'python python'
# 第一次按預設範圍統計'p'出現的次數,
# 第二次指定start=1,即從第二個字元開始統計。
name.count('p'), name.count('p', 1)
output:(2, 1)

str.find() & str.rfind()

1️⃣ find() 從左往右掃描字串,返回 sub 第一次出現的下標。可以通過 [start, end] 指定範圍,若不指定,則預設查詢整個字串。如最後未找到字串則返回 -1。

  • sub: 子串
  • start: 開始檢索的位置,預設為 0
  • end: 結束檢索的位置,預設為字串的長度
name = 'Python'
# 第一次按預設範圍查詢'Py'第一次出現的下標
# 第二次指定start=1,即從第二個字元開始查詢。
name.find('Py'), name.find('Py', 1)
output:(0, -1)

2️⃣ rfindfind() 的用法相似,只是從右往左開始掃描,即從字串末尾向字串首部掃描。

name = 'Python'
name.rfind('Py'), name.rfind('Py', 1)
output:(0, -1)

str.index() & str.rindex()

1️⃣ index()find() 用法相同,唯一的不同是如果找不到 sub 會報錯。

範例 🅰️

name = 'Python'
name.index('Py', 0)
output:0

範例 🅱️

name = 'Python'
name.index('Py', 1)
output:ValueError: substring not found

2️⃣ rindex()index() 用法相同,不過是從右邊開始查,它的查詢與 index() 相同。

name = 'Python'
name.rindex('Py', 0)
output:0

str.isalnum()

isalnum() 判斷字串中是否所有字元都是字母(可以為漢字)或數位,是 True ,否 False,空字串返回 False

範例 🅰️

'Python新視野'.isalnum()
output:True

範例 🅱️

'Python-sun'.isalnum()
output:False

'-' 是符號,所以返回 False


str.isalpha()

isalpha() 判斷字串中是否所有字元都是字母(可以為漢字),是 True ,否 False,空字串返回 False

範例 🅰️

'Python新視野'.isalpha()
output:True

範例 🅱️

'123Python'.isalpha()
output:False

其中包含了數位,返回 False


str.isdigit()

isdigit() 判斷字串中是否所有字元都是數位(Unicode數位,byte數位(單位元組),全形數位(雙位元組),羅馬數位),是 True ,否 False,空字串返回 False

範例 🅰️

'四123'.isdigit()
output:False

其中包含了漢字數位,返回 False


範例 🅱️

b'123'.isdigit()
output:True

byte 數位返回 True


str.isspace()

字串中只包含空格(\n\r\f\t\v),是 True ,否 False,空字串返回 False

符號含義
\n換行
\r回車
\f換頁
\t橫向製表符
\v縱向製表符
' \n\r\f\t\v'.isspace()
output:True

str.join()

join(iterable) 以指定字串作為分隔符,將 iterable 中所有的元素(必須是字串)合併為一個新的字串。

','.join(['Python', 'Java', 'C'])
output:‘Python,Java,C’

str.ljust() & str.rjust()

1️⃣ ljust() 返回一個指定寬度左對齊的字串

  • width:長度
  • fillchar:右部空餘部分填充的字元,預設使用空格
ljust_str = 'Python新視野'.ljust(15, "!")
ljust_str
output:‘Python新視野!!!!!!’

2️⃣ rjust() 返回一個指定寬度右對齊的字串,與 ljust 操作正好相反。

  • width:長度
  • fillchar:左部空餘部分填充的字元,預設使用空格
rjust_str = 'Python新視野'.rjust(15, "!")
rjust_str
output:’!!!!!!Python新視野’

str.lower() & str.islower()

1️⃣ lower() 將指定字串轉換為小寫。

lower_str = 'Python新視野'.lower()
lower_str
output:‘python新視野’

2️⃣ islower() 判斷字串所有區分大小寫的字元是否都是小寫形式,是 True ,否 False,空字串或字串中沒有區分大小寫的字元返回 False

'python-sun'.islower()
output:True

'python-sun' 區分大小寫的字元有 'pythonsun',並且都是小寫,所以返回 True


str.lstrip() & str.rstrip() & str.strip()

1️⃣ lstrip() 會在字串左側根據指定的字元進行擷取,若未指定預設擷取左側空餘(空格,\r,\n,\t等)部分。

name = '+++Python新視野+++'
name.lstrip('+')
output:‘Python新視野+++’

2️⃣ rstrip()lstrip() 用法相似,只是擷取右側的內容。

name = '+++Python新視野+++'
name.rstrip('+')
output:’+++Python新視野’

3️⃣ strip() 實際是 lstrip()rstrip() 的結合,它會擷取字串兩邊指定的字元。

name = '+++Python新視野+++'
name.strip('+')
output:‘Python新視野’

str.split() & str.splitlines()

1️⃣ str.split(sep=None, maxsplit=-1) 使用 sep 作為分隔符將字串進行分割,返回字串中的單詞列表。

  • seq: 用來分割字串的分隔符。None(預設值)表示根據任何空格進行分割,返回結果中不包含空格。
  • maxsplit: 指定最大分割次數。-1(預設值)表示不限制。
split_str = 'P y t h o n 新 視 野'
split_str.split(maxsplit=2)
output:[‘P’, ‘y’, ‘t h o n 新 視 野’]

使用預設的空格進行分割,設定最大的分割次數為2


2️⃣ str.splitlines 返回字串中的行列表,它按照行 ('\r',\n','\r\n') 分隔,返回分隔後的列表。它只有一個引數 keepends 表示是否在結果中保留換行符,False (預設)不保留,True 保留。

範例 🅰️

split_str = 'P\ny\r t h o n 新 視 野'
split_str.splitlines()
output:[‘P’, ‘y’, ’ t h o n 新 視 野’]

範例 🅱️

split_str = 'P\ny\r t h o n 新 視 野'
split_str.splitlines(keepends=True)
output:[‘P\n’, ‘y\r’, ’ t h o n 新 視 野’]

str.startswith() & str.endswith

1️⃣ startswith(prefix[, start[, end]]) 檢查字串是否是以指定子字串 substr 開頭,是 True ,否 False,空字串會報錯。如果指定 startend ,則在指定範圍內檢查。

startswith_str = 'Python新視野'
startswith_str.startswith('thon', 2)
output:True

從第 3 個字元開始檢測


2️⃣ str.endswith(suffix[, start[, end]])startswith 用法相同,不同之處是檢查字串是否以指定子字串結尾,是 True ,否 False,空字串會報錯。

endswith_str = 'Python新視野'
endswith_str.endswith('thon', 0, 6)
output:True

從第 1 個字元開始檢測,到第 7 個字元結束(不包含第 7 個),注意這裡的範圍和字串切片其實是一樣的道理,都是前閉後開。


str.title() & str.istitle()

1️⃣ title() 返回字串中每一個單詞首字母大寫。

title_str = 'python新視野 python新視野'.title()
title_str
output:‘Python新視野 Python新視野’

2️⃣ istitle() 判斷字串是否滿足每一個單詞首字母大寫,是 True ,否 False,空字串返回 False

'Abc Def  '.istitle()
output:True

str.upper() & str.isupper()

1️⃣ upper() 將指定字串中字母轉換為大寫。

upper_str = 'Python新視野'.upper()
upper_str
output:‘PYTHON新視野’

2️⃣ isupper() 判斷字串所有區分大小寫的字元是否都是大寫形式,是 True ,否 False,空字串或字串中沒有區分大小寫的字元返回 False

'PYTHON-SUN'.isupper()
output:True


列表操作

list()

list() 將可迭代物件轉成列表。

範例 🅰️

list((0,1,2)) + list({0,1,2}) + list('012')
output:[0, 1, 2, 0, 1, 2, ‘0’, ‘1’, ‘2’]

將彥祖、集合、字串轉換成列表並通過運運算元連線。


範例 🅱️

list(range(3))
output:[0, 1, 2]

將可迭代物件轉換成列表


list.append()

lst = ['Python', 'Java']
lst.append('C')
lst
output:[‘Python’, ‘Java’, ‘C’]

list.extend()

extend() 在列表的末尾新增可迭代物件(列表、元組、字典、字串)中的元素來擴充套件列表。

1️⃣ 追加列表

lst = ['Python', 'Java', 'C']
lst.extend([1, 2, 3])
lst
output:[‘Python’, ‘Java’, ‘C’, 1, 2, 3]

2️⃣ 追加字串

lst = ['Python', 'Java', 'C']
lst.extend('123')
lst
output:[‘Python’, ‘Java’, ‘C’, ‘1’, ‘2’, ‘3’]

將字串中的每一個字元當做一個元素追加到原列表末尾


3️⃣ 追加集合

lst = ['Python', 'Java', 'C']
lst.extend({1,2,3})
lst
output:[‘Python’, ‘Java’, ‘C’, 1, 2, 3]

4️⃣ 追加字典

lst = ['Python', 'Java', 'C']
lst.extend({1: 'b', 2: 'a'})
lst
output:[‘Python’, ‘Java’, ‘C’, 1, 2]

只將字典的 key 值追加到原列表末尾


list.insert()

insert(index, object) 將指定物件插入到列表的 index 位置,原本 index 位置上及 > index 的元素的元素整體後移。

範例 🅰️

lst = ['Python', 'Java', 'C']
lst.insert(1, 'C++')
lst
output:[‘Python’, ‘C++’, ‘Java’, ‘C’]

範例 🅱️

lst = ['Python', 'Java', 'C']
lst.insert(6, 'C++')
lst
output:[‘Python’, ‘Java’, ‘C’, ‘C++’]

index 的值大於列表長度時,會在列表末尾新增。


list.pop()

pop(index=-1) 移除列表中指定位置元素(預設最後一個),並且返回移除元素的值。若指定的 index 值超過列表長度則會報錯。

lst = ['Python', 'Java', 'C']
lst.pop(1), lst
output:(‘Java’, [‘Python’, ‘C’])

list.remove(元素)

lst.remove(value) 移除列表中第一次出現的 value ,無返回值,直接修改列表;如果 value 不在列表中則報錯。

範例 🅰️

lst = ['Python', 'Java', 'C', 'Python']
lst.remove('Python')
lst
output:[‘Java’, ‘C’, ‘Python’]

只刪除了第一次出現的 Python


範例 🅱️

lst = ['Python', 'Java', 'C', 'Python']
lst.remove('HTML')
lst
output:ValueError: list.remove(x): x not in list

HTML 不在列表中,發生錯誤


list.clear()

list.clear() 移除列表中所有的元素,無返回值。

lst = ['Python', 'Java', 'C']
lst.clear()
lst
output:[]

list.index()

index(value, start, stop) 返回列表中查詢的第一個與value匹配的元素下標,可通過 [start, stop) 指定查詢範圍。

範例 🅰️

lst = ['Python', 'Java', 'C',
	   'Python', 'Python']
lst.index('Python')
output:0

不指定範圍,在列表全部元素中查詢


範例 🅱️

lst = ['Python', 'Java', 'C',
	   'Python', 'Python']
lst.index('Python', 1, 3)
output:ValueError: ‘Python’ is not in list

指定範圍 [1, 3) ,即在[‘Java’, ‘C’]中查詢 Python 很明顯不存在,發生報錯


list.count()

count(value) 返回 value 在列表中出現的次數。若未在列表中找到 value 則返回 0 。

範例 🅰️

lst = ['Python', 'Java', 'C',
	   'Python', 'Python']
lst.count('Python')
output:3

範例 🅱️

lst = ['Python', 'Java', 'C',
	   'Python', 'Python']
lst.count('Py')
output:0

列表中無元素 'Py',返回 0 。


list.reverse()

reverse() 將列表逆序排列,無返回值。

lst = [1, 5, 9, 2]
lst.reverse()
lst
output:[2, 9, 5, 1]

list.sort()

sort() 對列表進行指定方式的排序,修改原列表,該排序是穩定的(即兩個相等元素的順序不會因為排序而改變)。

  • key: 指定可迭代物件中的每一個元素來按照該函數進行排序
  • reverse: False 為升序,True 為降序。

範例 🅰️

lst = [1, 5, 9, 2]
lst.sort()
lst
output:[1, 2, 5, 9]

範例 🅱️

lst = ['Python', 'C', 'Java'] 
lst.sort(key=lambda x:len(x), reverse=False)
lst
output:[‘C’, ‘Java’, ‘Python’]

指定 key 計算列表中每個元素的長度,並按照長度進行升序排序


list.copy()

copy() 對列表進行拷貝,返回新生成的列表,這裡的拷貝是淺拷貝,下面會說明為什麼特意說它是淺拷貝

範例 🅰️

lst = [[1,2,3], 'a' ,'b']
lst_copy = lst.copy()
lst_copy.pop()
lst, lst_copy
output:([[1, 2, 3], ‘a’, ‘b’], [[1, 2, 3], ‘a’])

lst 進行 copy ,然後刪除列表 lst_copy 的最後一個元素,此時的 lst 的最後一個元素並未被刪除,說明兩個列表指向的地址確實不一樣。


範例 🅱️

lst = [[1,2,3], 'a' ,'b']
lst_copy = lst.copy()
lst_copy[0].pop()
lst_copy.pop()
lst, lst_copy
output:([[1, 2], ‘a’, ‘b’], [[1, 2], ‘a’, ‘b’])

這裡執行和上一個範例一樣的操作,只是這次再刪除一個資料,即列表巢狀的子列表中最後一個元素,觀察結果,發現這時不僅僅是 lst_copy 的列表發生改變,原列表 lst 中巢狀的字列表也發生了改變。說明兩個列表指向的地址不一樣,但子列表中指向的地址是相同的。


擴充套件:直接賦值、淺拷貝、深拷貝

(1)直接賦值,傳遞物件的參照而已。原始列表改變,被賦值的物件也會做相同改變。

(2)淺拷貝,沒有拷貝子物件,所以原始資料子物件改變,拷貝的子物件也會發生變化。

(3)深拷貝,包含物件裡面的子物件的拷貝,所以原始物件的改變不會造成深拷貝里任何子元素的改變,二者完全獨立。

1️⃣ 先看直接賦值

lst = [1,2,3,[1,2]]
list1 = lst

# --直接賦值--
lst.append('a')
list1[3].append('b')

print(lst,'地址:',id(lst))   
print(list1,'地址:',id(list1))
# [1, 2, 3, [1, 2, 'b'], 'a'] 地址: 2112498512768
# [1, 2, 3, [1, 2, 'b'], 'a'] 地址: 2112498512768

無論 lst 還是 list1 發生改變,二者都會受到影響。


2️⃣ 淺拷貝需要用到 copy 模組,或者用 list.copy() 效果一樣

from copy import copy

lst = [1, 2, 3, [1, 2]]
list2 = copy(lst)

# --淺拷貝--
lst.append('a')
list2[3].append('b')

print(lst,'地址:',id(lst))
print(list2,'地址:',id(list2))
# [1, 2, 3, [1, 2, 'b'], 'a'] 地址: 2112501949184
# [1, 2, 3, [1, 2, 'b']] 地址: 2112495897728

lstlist2 地址不同,但子列表的地址仍是相同的,修改子列表中的元素時,二者都會受到影響。


3️⃣ 深拷貝需要用到 copy 模組中的 deepcopy ,此時兩個列表完全獨立。

from copy import deepcopy

lst = [1, 2, 3, [1, 2]]
list3 = deepcopy(lst)

# --深拷貝--
lst.append('a')
list3[3].append('b')

print(lst,'地址:',id(lst))
print(list3,'地址:',id(list3))
# [1, 2, 3, [1, 2], 'a'] 地址: 2112506144192
# [1, 2, 3, [1, 2, 'b']] 地址: 2112499460224

根據結果可以看到修改子列表中的值時,原列表未發生改變。



元組

tuple()

tuple() 將可迭代物件轉換成元組。

tuple([0,1,2]) + tuple(range(3)) + tuple({0,1,2}) + tuple('012')
output:(0, 1, 2, 0, 1, 2, 0, 1, 2, ‘0’, ‘1’, ‘2’)

將可迭代物件轉換成列表並通過運運算元連線。



字典

dict.clear()

clear() 清除字典的所有內容。

dic = {'CSDN': 'Dream丶killer',
       '公眾號': 'Python新視野'}
dic.clear()
dic
output:{}

dict.fromkeys()

fromkeys() 建立一個新字典,以序列 iterable 中元素做字典的鍵,value 為字典所有鍵對應的初始值。

  • iterable: 可迭代物件,新字典的鍵。
  • value: 可選引數, 設定鍵序列對應的值,預設為 None
dict.fromkeys(['CSDN', '公眾號'],
              'Python新視野')
output:{‘CSDN’: ‘Python新視野’, ‘公眾號’: ‘Python新視野’}

dict.get()

get(key, default=None) 根據指定的 key 值查詢,如果 key 在字典中,則返回 key 的值,否則為 None

範例 🅰️

dic = {'CSDN': 'Dream丶killer',
       '公眾號': 'Python新視野'}
dic.get('CSDN')
output:‘Dream丶killer’

範例 🅱️

dic = {'CSDN': 'Dream丶killer',
       '公眾號': 'Python新視野'}
print(dic.get('微信'))
output:None

字典中沒有 key 等於 '微信',返回 None,jupyter notebook 對於 None 如果不加 print 預設不輸出,所以這裡加上print 來列印結果


dict.items()

items() 返回檢視物件,是一個可遍歷的 key/value 對,可以使用 list() 將其轉換為列表。

範例 🅰️

dic = {'CSDN': 'Dream丶killer',
       '公眾號': 'Python新視野'}
list(dic.items())
output:[(‘CSDN’, ‘Dream丶killer’), (‘公眾號’, ‘Python新視野’)]

範例 🅱️

dic = {'CSDN': 'Dream丶killer',
       '公眾號': 'Python新視野'}
for key, value in dic.items():
    print('key: ', key, 'value: ', value)

# key:  CSDN value:  Dream丶killer
# key:  公眾號 value:  Python新視野

dict.keys()

keys() 返回一個檢視物件,值為字典的 key ,可將其轉換成列表。

dic = {'CSDN': 'Dream丶killer',
       '公眾號': 'Python新視野'}
dic.keys()
output:dict_keys([‘CSDN’, ‘公眾號’])

dict.setdefault()

setdefault(key, default=None) 如果鍵不在字典中,則插入值為 None 的鍵。如果鍵在字典中,則返回鍵的值。

範例 🅰️

dic = {'CSDN': 'Dream丶killer',
       '公眾號': 'Python新視野'}
dic.setdefault('CSDN', 'python-sun')
output:‘Dream丶killer’

字典中有 CSDN 這個 key 值,返回 CSDN 對應的值,不需要插入


範例 🅱️

dic = {'CSDN': 'Dream丶killer',
       '公眾號': 'Python新視野'}
dic.setdefault('微信', 'python-sun')
dic
output:{‘CSDN’: ‘Dream丶killer’, ‘公眾號’: ‘Python新視野’, ‘微信’: ‘python-sun’}

字典中沒有 微信 這個 key 值,返回 None ,執行插入,並根據設定的引數 python-sun 來進行賦值。


dict.update()

dict.update(dict1) 把字典 dict1key/value 對更新到 dict 裡,當 dict1key 出現在 dict 中則修改 dict 中的值,如果 key 沒有出現在 dict 中,則新增這一對 key/value

dic = {'CSDN': 'Dream丶killer',
       '公眾號': 'Python新視野'}
dic1 = {'CSDN': 'new_name',
        '微信': 'python-sun'}
dic.update(dic1)
dic
output:{‘CSDN’: ‘new_name’, ‘公眾號’: ‘Python新視野’, ‘微信’: ‘python-sun’}

dict.values()

values() 返回一個檢視物件,值為字典的 value ,可將其轉換成列表。

dic = {'CSDN': 'Dream丶killer',
       '公眾號': 'Python新視野'}
dic.values()
output:dict_values([‘Dream丶killer’, ‘Python新視野’])

dict.pop()

pop() 刪除指定 keykey/value ,如果 key 沒有找到,則報錯。

dic = {'CSDN': 'Dream丶killer',
       '公眾號': 'Python新視野'}
dic.pop('CSDN')
dic
output:{‘公眾號’: ‘Python新視野’}

dict.popitem()

popitem() 刪除字典中末尾的元素,並返回一個元組的(鍵,值)對。字典為空則報錯。

dic = {'CSDN': 'Dream丶killer',
       '公眾號': 'Python新視野'}
dic.popitem()
output:(‘公眾號’, ‘Python新視野’)


集合

set.add()

向集合中新增一個元素,但如果該元素已經出現在集合中,則不起作用。

範例 🅰️

set1 = {'Dream丶Killer',
        'Python新視野',
        'python-sun'}
set1.add('python')
set1
output:{‘Dream丶Killer’, ‘Python新視野’, ‘python’, ‘python-sun’}

範例 🅱️

set1 = {'Dream丶Killer',
        'Python新視野',
        'python-sun'}
set1.add('python-sun')
set1
output:{‘Dream丶Killer’, ‘Python新視野’, ‘python-sun’}

新增的元素 python-sun 已經出現在集合中,所以 set1 不發生變化


set.clear()

clear() 移除集合中的所有元素。

set1 = {'Dream丶Killer',
        'Python新視野',
        'python-sun'}
set1.clear()
set1
output:set()

set.difference() & set.difference_update()

1️⃣ difference() 返回多個集合的差集,通俗來講就是返回第一個 set 中哪些元素沒有在其他 set 中出現。

範例 🅰️

set1 = {'Dream丶Killer',
        'Python新視野',
        'python-sun'}
set2 = {'python', 'Dream丶Killer'}
set3 = {'Python新視野'}
set1.difference(set2, set3)
output:{‘python-sun’}

set1 中的元素只有 python-sun 沒有在 set2set3 中出現過,所以以及集合的形式返回 {'python-sun'}


範例 🅱️

set1 = {'Dream丶Killer',
        'Python新視野',
        'python-sun'}
set2 = {'python', 'Dream丶Killer'}
set3 = {'Python新視野', 'python-sun'}
set1.difference(set2, set3)
output:set()

set1 中的元素都在 set2set3 中出現過,所以返回空集合 set()


2️⃣ difference_update() 方法與 difference() 方法的區別在於 difference() 方法返回一個移除相同元素的新集合,而 difference_update() 方法是直接移除原集合中的元素,無返回值。

範例 🅰️

set1 = {'Dream丶Killer',
        'Python新視野',
        'python-sun'}
set2 = {'python', 'Dream丶Killer'}
set3 = {'Python新視野'}
set1.difference_update(set2, set3)
set1
output:{‘python-sun’}

set1 中的元素 Dream丶KillerPython新視野 都有在 set2set3 中出現過,所以從 set1 中移除這些值


範例 🅱️

set1 = {'Dream丶Killer',
        'Python新視野',
        'python-sun'}
set2 = {'python', 'Dream丶Killer'}
set3 = {'Python新視野', 'python-sun'}
set1.difference_update(set2, set3)
set1
output:set()

set1 中的元素都在 set2set3 中出現過,set1 移除所有值後為空集合 set()


set.discard()

discard() 刪除集合中指定的元素。如果指定移除的元素不在集合中,則不移除。

範例 🅰️

set1 = {'Dream丶Killer',
        'Python新視野',
        'python-sun'}
set1.discard('Dream丶Killer')
set1
output:{‘Python新視野’, ‘python-sun’}

指定的元素存在於 set1 ,將它存 set1 中移除


範例 🅱️

set1 = {'Dream丶Killer',
        'Python新視野',
        'python-sun'}
set1.discard('python')
set1
output:{‘Dream丶Killer’, ‘Python新視野’, ‘python-sun’}

指定的元素不在 set1 內,set1 不做改變


set.intersection() & set.intersection_update()

1️⃣ intersection() 返回集合的交集。沒有交集則返回空集 set()

set1 = {'Dream丶Killer',
        'Python新視野',
        'python-sun'}
set2 = {'python-sun', 'Dream丶Killer'}
set3 = {'Python新視野', 'python-sun'}
set1.intersection(set2, set3)
output:{‘python-sun’}

返回 set1set2set3 中同時出現的元素


2️⃣ intersection_update() 方法與 intersection() 方法的區別在於 intersection() 方法將集合的交集作為新集合返回,而 intersection_update() 方法是直接修改原集合中的元素,只保留交集元素,無返回值。

set1 = {'Dream丶Killer',
        'Python新視野',
        'python-sun'}
set2 = {'python-sun', 'Dream丶Killer'}
set3 = {'Python新視野', 'python-sun'}
set1.intersection_update(set2, set3)
set1
output:{‘python-sun’}

set1 中只有 'python-sun 同時在 set2set3 中出現過,因此移除 set1 中其他元素


set.isdisjoint()

isdisjoint() 判斷兩個集合是否包含相同的元素,有則返回 True,無則返回 False
範例 🅰️

set1 = {'Dream丶Killer',
        'Python新視野',
        'python-sun'}
set2 = {'python-sun', 'Dream丶Killer'}
set1.isdisjoint(set2)
output:False

set1set2 中有兩個相同元素,返回 False


範例 🅱️

set1 = {'Dream丶Killer',
        'Python新視野',
        'python-sun'}
set2 = {'python'}
set1.isdisjoint(set2)
output:True

set1set2 中無相同元素,返回 True


set.issubset()

set2.issubset(set1) 判斷集合 set2 是否為 set1 集合的子集。是則返回 True,否則返回 False

set1 = {'Dream丶Killer',
        'Python新視野',
        'python-sun'}
set2 = {'python-sun', 'Dream丶Killer'}
set2.issubset(set1)
output:True

set2set1 集合的子集,故返回 True ,使用時需注意 set1set2 的位置順序。如果寫成 set1.issubset(set2) 則會返回 False


set.issuperset()

set1.issuperset(set2) 判斷集合 set2 是否為 set1 集合的子集。是則返回 True,否則返回 False。它與 issubset() 用法相同,只有引數的位置相反而已。

set1 = {'Dream丶Killer',
        'Python新視野',
        'python-sun'}
set2 = {'python-sun', 'Dream丶Killer'}
set1.issuperset(set2)
output:True

set1.pop()

pop() 移除並返回集合中的任意元素。如果該集合為空集則報錯。

set1 = {'Dream丶Killer',
        'Python新視野',
        'python-sun'}
set1.pop()
output:‘python-sun’

set.remove()

remove() 從集合中移除指定的元素,如果該元素不在集合中,則發生報錯。

set1 = {'Dream丶Killer',
        'Python新視野',
        'python-sun'}
set1.remove('Dream丶Killer')
set1
output:{‘Python新視野’, ‘python-sun’}

set.symmetric_difference()

symmetric_difference() 返回兩個集合中不重複的元素集合,即兩個集合的補集,與 ^ 的作用相同。

範例 🅰️

set1 = {'Dream丶Killer',
        'Python新視野',
        'python-sun'}
set2 = {'python', 'python-sun', 'Dream丶Killer'}
set1.symmetric_difference(set2)
output:{‘Python新視野’, ‘python’}

範例 🅱️

set1 = {'Dream丶Killer',
        'Python新視野',
        'python-sun'}
set2 = {'python',
	    'python-sun',
	    'Dream丶Killer'}
set1 ^ set2
output:{‘Python新視野’, ‘python’}

結果與上面相同


set.symmetric_difference_update()

set1.symmetric_difference_update(set2) 移除 set1 中在 set2 相同的元素,並將 set2 集合中不同的元素插入到 set1 中。簡單來說就是把 set1set2 的補集賦值給 set1

範例 🅰️

set1 = {'Dream丶Killer',
        'Python新視野',
        'python-sun'}
set2 = {'python',
		'python-sun',
		'Dream丶Killer'}
set1.symmetric_difference_update(set2)
set1
output:{‘Python新視野’, ‘python’}

範例 🅱️

set1 = {'Dream丶Killer',
        'Python新視野',
        'python-sun'}
set2 = {'python',
		'python-sun',
		'Dream丶Killer'}
set1 = set1 ^ set2
set1
output:{‘Python新視野’, ‘python’}

set.union()

union() 返回多個集合的並集。與 | 的作用相同。

範例 🅰️

set1 = {'Dream丶Killer',
        'Python新視野',
        'python-sun'}
set2 = {'python',
		'python-sun',
		'Dream丶Killer'}
set3 = {'ABC'}
set1.union(set2, set3)
output:{‘ABC’, ‘Dream丶Killer’, ‘Python新視野’, ‘python’, ‘python-sun’}

範例 🅱️

set1 = {'Dream丶Killer',
        'Python新視野',
        'python-sun'}
set2 = {'python',
		'python-sun',
		'Dream丶Killer'}
set3 = {'ABC'}
set1 | set2 | set3
output:{‘ABC’, ‘Dream丶Killer’, ‘Python新視野’, ‘python’, ‘python-sun’}

set.update()

update() 使用本身和其他的聯合來更新集合。

範例 🅰️

set1 = {'Dream丶Killer',
        'Python新視野',
        'python-sun'}
set1.update([1,2,3])
set1
output:{1, 2, 3, ‘Dream丶Killer’, ‘Python新視野’, ‘python-sun’}

範例 🅱️

set1 = {'Dream丶Killer',
        'Python新視野',
        'python-sun'}
set1 = set1 | set([1,2,3])
set1
output:{1, 2, 3, ‘Dream丶Killer’, ‘Python新視野’, ‘python-sun’}

使用 | 也可以達到相同的效果。



對於剛入門 Python 或是想要入門 Python 的小夥伴,可以通過下方小卡片聯絡作者,一起交流學習,都是從新手走過來的,有時候一個簡單的問題卡很久,但可能別人的一點撥就會恍然大悟,由衷的希望大家能夠共同進步。

👇🏻 關注小卡片,一起學習Python👇🏻