👉跳轉文末👈 獲取作者聯系方式,共同學習進步
文章目錄
- 運行環境
- 輸入輸出函式
- print()
- input()
- 獲取資料型別
- type()
- isintance()
- 字串操作
- str()
- eval()
- str.capitalize()
- str.center()
- str.count()
- str.find() & str.rfind()
- str.index() & str.rindex()
- str.isalnum()
- str.isalpha()
- str.isdigit()
- str.isspace()
- str.join()
- str.ljust() & str.rjust()
- str.lower() & str.islower()
- str.lstrip() & str.rstrip() & str.strip()
- str.split() & str.splitlines()
- str.startswith() & str.endswith
- str.title() & str.istitle()
- str.upper() & str.isupper()
- 串列操作
- list()
- list.append()
- list.extend()
- list.insert()
- list.pop()
- list.remove(元素)
- list.clear()
- list.index()
- list.count()
- list.reverse()
- list.sort()
- list.copy()
- 擴展:直接賦值、淺拷貝、深拷貝
- 元組
- tuple()
- 字典
- dict.clear()
- dict.fromkeys()
- dict.get()
- dict.items()
- dict.keys()
- dict.setdefault()
- dict.update()
- dict.values()
- dict.pop()
- dict.popitem()
- 集合
- set.add()
- set.clear()
- set.difference() & set.difference_update()
- set.discard()
- set.intersection() & set.intersection_update()
- set.isdisjoint()
- set.issubset()
- set.issuperset()
- set1.pop()
- set.remove()
- set.symmetric_difference()
- set.symmetric_difference_update()
- set.union()
- set.update()
運行環境
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) 回傳 sub 在 str 中出現的次數,可以通過 [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?? rfind 與 find() 的用法相似,只是從右往左開始掃描,即從字串末尾向字串首部掃描,
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,空字串會報錯,如果指定 start 和 end ,則在指定范圍內檢查,
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
lst 與 list2 地址不同,但子串列的地址仍是相同的,修改子串列中的元素時,二者都會受到影響,
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) 把字典 dict1 的 key/value 對更新到 dict 里,當 dict1 的 key 出現在 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() 洗掉指定 key 的 key/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 沒有在 set2 與 set3 中出現過,所以以及集合的形式回傳 {'python-sun'}
示例 🅱?
set1 = {'Dream丶Killer',
'Python新視野',
'python-sun'}
set2 = {'python', 'Dream丶Killer'}
set3 = {'Python新視野', 'python-sun'}
set1.difference(set2, set3)
| output:set() |
|---|
set1 中的元素都在 set2 與 set3 中出現過,所以回傳空集合 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丶Killer 與 Python新視野 都有在 set2 與 set3 中出現過,所以從 set1 中移除這些值
示例 🅱?
set1 = {'Dream丶Killer',
'Python新視野',
'python-sun'}
set2 = {'python', 'Dream丶Killer'}
set3 = {'Python新視野', 'python-sun'}
set1.difference_update(set2, set3)
set1
| output:set() |
|---|
set1 中的元素都在 set2 與 set3 中出現過,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’} |
|---|
回傳 set1、set2、set3 中同時出現的元素
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 同時在 set2 與 set3 中出現過,因此移除 set1 中其他元素
set.isdisjoint()
isdisjoint() 判斷兩個集合是否包含相同的元素,有則回傳 True,無則回傳 False,
示例 🅰?
set1 = {'Dream丶Killer',
'Python新視野',
'python-sun'}
set2 = {'python-sun', 'Dream丶Killer'}
set1.isdisjoint(set2)
| output:False |
|---|
set1 與 set2 中有兩個相同元素,回傳 False
示例 🅱?
set1 = {'Dream丶Killer',
'Python新視野',
'python-sun'}
set2 = {'python'}
set1.isdisjoint(set2)
| output:True |
|---|
set1 與 set2 中無相同元素,回傳 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 |
|---|
set2 是 set1 集合的子集,故回傳 True ,使用時需注意 set1 與 set2 的位置順序,如果寫成 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 中,簡單來說就是把 set1 與 set2 的補集賦值給 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 的小伙伴,可以通過下方小卡片聯系作者,一起交流學習,都是從新手走過來的,有時候一個簡單的問題卡很久,但可能別人的一點撥就會恍然大悟,由衷的希望大家能夠共同進步,
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/317989.html
標籤:其他
