基礎數據結構方法匯總
字符串方法:
mystr.capitalize() 第一個字符轉換為大寫,其它都轉為小寫(本來的大寫字母也轉為小寫) "ab C d" --> Ab c d
a_str = 'hello hello'
# 1.統計字符串長度
len(a_str) # 長度 11
# 2.統計某子字符串出現的次數
a_str.count('ll') # 2 子字符串 ll 在 a_str 中出現了 2 次
a_str.count('abc') # 0 子字符串 abc 在 a_str 中出現了 0 次
# 3.查找某子字符串(第一次)出現的位置
a_str.index('lo') # 3 子字符串 lo 第一次在 a_str 中出現的索引為 3
a_str.index('abc') # 出錯 ValueError: substring not found
a_str.index('lo', 4) # 9 起始索引為4,子字符串 lo 第一次出現的索引為 9。
a_str.index('lo', 4, 8) # ValueError: substring not found 范圍 4~8 之間找不到子字符串
# 4.判斷類型的方法
a_str.isspace() # ' \n\r\t'.isspace() # True 空格、換行、回車、制表符 print(' \n \r\r \t'.isspace()) True
a_str.isalpha() # 非空,且都為字母,返回 True
a_str.isalnum() # 判斷是否為 alpha 和 number
a_str.isdecimal() # 只含數字、全角數字 print('0o12'.isdecimal()) # False 不能判斷小數
a_str.isdigit() # 只含數字、全角數字、⑴、\u00b2 不能判斷小數
a_str.isnumeric() # 只含數字、全角數字、漢字數字 一二三 不能判斷小數
a_str.istitle()
a_str.islower()
a_str.isupper()
a_lst = [1, 1.1, '1', '⑴', '\u00b2', 'Ⅲ', '一千二百'] # 整數、小數、全角....
b_lst = ['isdecimal', 'isdigit', 'isnumeric']
for f in b_lst:
for n in a_lst:
func = f"'{n}'.{f}()"
print(eval(func), end='\t')
print()
# 5.查找和替換
a_str.startswith('he') # True # a_str.startswith('He') False 區分大小寫
a_str.endswith('he') # False
a_str.find('li') # 2 # a_str.find('li') 不存在的字符串,不會像 index 報錯,而是返回 -1
a_str.find('li',5) # 從5開始查找
a_str.find('li',5,9) # 查找 5-9 之間的元素 (不含9元素:范圍前閉后開)
a_str.rfind('llo') # 8 從 右邊 開始查找
a_str.index('l')
a_str.rindex('l')
new_str = a_str.replace('llo', 'new') # 需要用變量接收結果 # henew henew
'ab' in 'abcd'
# 6.大小寫轉換
a_str.capitalize()
a_str.title()
a_str.lower()
a_str.upper()
a_str.swapcase()
# 7.文本對齊
a_str.center(width) # a_str.center(width,'-') 用 - 填充
a_str.ljust(width)
a_str.rjust(width)
# 8.去除空白
a_str.strip() # print('\n \t \rTink this \t'.strip()) # 左右兩端的空格、換行、回車、制表符被去掉。Tink this
a_str.lstrip()
a_str.rstrip()
# 9.拆分和連接
a_str.split() # print("this\nis a\rcat\tand".split()) # ['this', 'is', 'a', 'cat', 'and'] 返回列表
a_str.split('ll') # ['he', 'o he', 'o'] # 無參數 默認 空格分割
a_str.join() # ''.join(序列)
a_str.splitlines() # 按行切分
a_str.partition('ll') # ('he', 'll', 'o hello') 返回一個3元的元組
a_str.rpartition('ll') # ('hello he', 'll', 'o') 從右邊開始
另有: 'ab' in 'abcd'
列表方法:(增刪查改)
新增:
lst.append(obj) 在末尾追加數據
lst.insert(下標,obj) 如果下標不存在,則會插入到列表的末尾。支持反向索引,超出范圍就會在列表的頭部
lst.extend(obj)
print([1, 2] + [3, 4]) # [1, 2, 3, 4]
print(['a', 'b'] + [1, True]) # ['a', 'b', 1, True]
lst = list("HIL") # ['H', 'I', 'L']
lst[1:1] = list("Tom") # ['H', 'T', 'o', 'm', 'I', 'L']
lst[2:4] = [] # ['H', 'T', 'I', 'L']
刪除:
lst.pop() 刪除最后一個元素 相當于lst.pop(-1)
lst.pop(下標) 若下標不存在,IndexError
lst.remove(obj) 若obj不存在,則會引發ValueError異常
del lst[下標] 若下標不存在,IndexError
lsr.clear() 清空列表
修改:
lst[下標] = obj
lst.count(obj) 元素obj不存在,結果為0
lst.index(obj) 元素obj不存在,則會引發ValueError異常
lst.reverse() 元素翻轉
lst.sort()
列表元素查找:
in、not in
count 結合 index 使用
index = a_list.index('a') if ('a' in a_list) else -1
[x for x in test if 'a' in x]
lst.append(obj)
https://runestone.academy/ns/books/published/thinkcspy/index.html
ThinkCSPY
https://runestone.academy/ns/books/published/pythonds/index.html
PythonDS
# 字典:鍵不可變類型;鍵不重復,鍵重復會覆蓋;3.6版本以后的字典是有序的
d1 = {} # 定義空字典
d2 = dict() # 定義空字典
d3 = {
"name": "王大錘", # 鍵必須不可變(不可變類型:int、bool、str、tuple等;可變類型:list、set、dict)
"age": 12,
"hobby": ['看書', '畫畫'], # 值可以是列表
123: 990, # 鍵為 int 類型 123
(123,): {"ad1": "浦西", "ad2": "浦東"}, # 鍵為 tuple類型。 值可以是字典
True: "孫悟空",
1: "齊天大圣" # 1 會把上一條 True 覆蓋掉。 True 和 1 等效
}
# 通過 dict.fromkeys(seq[, value])) 創建字典
d4: dict = dict.fromkeys(['A', 'B']) # {'A': None, 'B': None} 默認值為None
d5: dict = dict.fromkeys(['A', 'B'], '沒維護') # {'A': '沒維護', 'B': '沒維護'}
# 以下 測試用,實用少。了解即可
d6 = dict([('a', 1), ('b', 2)]) # {'a': 1, 'b': 2}
d7 = dict([['a', 1], ['b', 2]]) # {'a': 1, 'b': 2}
d8 = dict((['a', 1], ['b', 2], ('c', 3))) # {'a': 1, 'b': 2, 'c': 3}
d9 = dict(zip(list("ABCDE"), list("1234"))) # {'A': '1', 'B': '2', 'C': '3', 'D': '4'}
# 獲取值
print(d3[True], d3[1]) # 齊天大圣 齊天大圣
print(d3['email']) # KeyError: 'email'。 鍵不在字典中時,會觸發 KeyError 異常
# get()方法語法:dict.get(key[, value]) 獲取值
print(d3.get('name')) # 王大錘 get方法獲取鍵對應的值
print(d3.get('email')) # None 若get方法獲取的鍵不存在,返回None。 不會引發異常
print(d3.get('email', 'hi@qq.com')) # hi@qq.com 若email鍵不存在,返回指定的默認值hi@qq.com,而不再返回None。 不會修改字典
print(d3.get((123,)).get('ad1')) # 浦西 獲取嵌套字典里的值。鏈式調用
# 獲取所有鍵
print(d3.keys()) # dict_keys(['name', 'age', 'hobby', 123, (123,), True])
print('age' in d3.keys()) # True 存在 age 鍵 。等效于 'age' in d3
print('email' in d3.keys()) # False 不存在 email 鍵
# 獲取所有值
print(d3.values()) # dict_values(['王大錘', 12, ['看書', '畫畫'], 990, {'ad1': '浦西', 'ad2': '浦東'}, '齊天大圣'])
print('孫悟空' in d3.values()) # False
print('齊天大圣' in d3.values()) # True
# 獲取所有鍵值對
d5_k_v = d5.items() # dict_items([('A', '沒維護'), ('B', '沒維護')])
for k, v in d5_k_v:
print(k, v)
for k, v in d5.items():
print(k, v)
# setdefalt 可視為新增 若鍵存在,不修改;若鍵不存在,新增并賦值
d5.setdefault('A', 999) # {'A': '沒維護', 'B': '沒維護'} 鍵 A 已存在,不改變原值
d5.setdefault('C', 'Hi') # {'A': '沒維護', 'B': '沒維護', 'C': 'Hi'} 鍵 C 不存在,創建并賦值 Hi
d5.update(d4) # {'A': None, 'B': None, 'C': 'Hi'} 用 d4 字典更新 d5
d4.setdefault(120, 'Call') # d4 ----> {'A': None, 'B': None, 120: 'Call'}
d5.update(d4) # d5 ----> {'A': None, 'B': None, 'C': 'Hi', 120: 'Call'} 用 d4 字典更新 d5
d5_poped = d5.pop('C') # d5 ----> {'A': None, 'B': None, 120: 'Call'} pop方法,移除指定鍵值對
print(d5_poped) # Hi
d5.pop('hello') # 若不存在,引發異常 KeyError: 'hello'
d5_poped = d5.popitem() # 3.6版本以前隨機刪除一項;3.6(字典是有序的)及以后版本刪除最后一項
print(d5) # d5 ----> {'A': None, 'B': None} 刪除最后一項,且以元組形式返回刪除的鍵值對
print(d5_poped) # (120, 'Call')
print(len(d3)) # 6 字典d3的長度
print('age' in d3) # True 和下面一句等效。判斷一個值是否在字典里,是默認以key去判斷
print('age' in d3.keys()) # True
print(('age', 12) in d3.items()) # True
print(('age', 16) in d3.items()) # False
print(['age', 12] in d3.items()) # False
# 存在則修改,不存在則新增
d3['age'] = 20 # d3 --> {'name': '王大錘', 'age': 20, 'hobby': ['看書', '畫畫'], 123: 990, (123,): {'ad1': '浦西', 'ad2': '浦東'}, True: '齊天大圣'}
d3['gender'] = '男' # d3 --> {'name': '王大錘', 'age': 20, 'hobby': ['看書', '畫畫'], 123: 990, (123,): {'ad1': '浦西', 'ad2': '浦東'}, True: '齊天大圣', 'gender': '男'}
del d3['gender'] # d3 --> {'name': '王大錘', 'age': 20, 'hobby': ['看書', '畫畫'], 123: 990, (123,): {'ad1': '浦西', 'ad2': '浦東'}, True: '齊天大圣'}
del d3['no_have'] # 若不存在,報錯 KeyError: 'no_have'。 用的比pop更多,但pop有返回值
for i in d3: # 對鍵循環遍歷。等效于 for i in d3.keys()
print(i)
for i in d3.values():
print(i)
for k, v in d3.items():
print(k, '-->', v)
print(d3)
#####################################################
#######################################################
# 集合特性:元素無序、元素可變、元素不可重復
# 定義
s = set() # 定義空集合
# 增加元素
s.add('小王') # {'小王'}
s.add('小張') # {'小張', '小王'}
s.discard('小張') # {'小王'} 刪除元素:小張 discard:丟棄
s2 = {'小王', '小劉', '小孫'}
print(s & s2) # {'小王'} 兩集合取交集
s.add('小孫')
print(s & s2) # {'小孫', '小王'}
print(s.intersection(s2)) # {'小孫', '小王'} 取交集方法2
s.add('Tom') # s --> {'Tom', '小孫', '小王'}
print(s) # {'Tom', '小孫', '小王'}
print(s2) # {'小劉', '小孫', '小王'}
print(s | s2) # {'小劉', '小孫', '小王', 'Tom'} 并集
print(s.union(s2)) # {'小劉', '小孫', '小王', 'Tom'} 并集 方法2
print(s - s2) # {'Tom'} 差集 s中有但s2中沒有的集合
print(s2.difference(s)) # {'小劉'}差集 s2中有但s中沒有的集合
print(len(s)) # 3 集合s中元素個數
for i in s: # 遍歷集合
print(i)
astr = "上海自來水來自海上"
sstr = set(astr) # {'水', '自', '海', '上', '來'} # 字符串轉集合
alst = ' a big black bear sat on a big black bug'.strip().split()
# ['a', 'big', 'black', 'bear', 'sat', 'on', 'a', 'big', 'black', 'bug']
slst = set(alst) # {'sat', 'big', 'a', 'black', 'bear', 'bug', 'on'} 列表轉集合
print(slst)
w_lst = [11, 22, ['Mon', 'Fri'], 44] # 列表嵌套
set(w_lst) # 轉換失敗 TypeError: unhashable type: 'list' 集合元素不能是list
# 和字典一樣,查詢速度快(依賴于哈希存儲)
# 若判斷一個元素在不在一個序列里面,盡可能使用集合,因集合效率更高
s3 = {True, 1} # True 和 False 本質上存儲的是 1 和 0
print(s3) # {True} 經過去重,只保留最先出現的 True
s4 = {1, True, False, 0}
print(s4) # {False, 1} 只保留最先出現的值
########################################################
####################################################
# 利用 集合、列表 統計
d_str = 'asdfghgfdedacsw'
set5 = set()
lst_a = []
for i in d_str:
if i in set5:
lst_a.append(i)
else:
set5.add(i)
for i in set5:
print("%s-->%s " % (i, lst_a.count(i) + 1), end=' ')
# e-->1 g-->2 d-->3 s-->2 a-->2 f-->2 c-->1 h-->1 w-->1
d0: dict = dict.fromkeys(set5, 1) # 通過集合創建字典,且賦初始值為 1
for i in d0:
d0[i] += lst_a.count(i)
print(d0) # {'e': 1, 'g': 2, 'd': 3, 's': 2, 'a': 2, 'f': 2, 'c': 1, 'h': 1, 'w': 1}
a_str.center(width)

浙公網安備 33010602011771號