Python 100個常用函數全面解析
1. 類型轉換函數
1.1 int()
將字符串或數字轉換為整數。
# 基本用法
int('123') # 123
int(3.14) # 3# 指定進制轉換
int('1010', 2) # 10 (二進制轉十進制)
int('FF', 16) # 255 (十六進制轉十進制)# 臨界值處理
int('') # ValueError: invalid literal for int() with base 10: ''
int(None) # TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
int('3.14') # ValueError: invalid literal for int() with base 10: '3.14'
int(float('inf')) # OverflowError: cannot convert float infinity to integer
1.2 float()
將數據轉換為浮點數。
# 基本用法
float('3.14') # 3.14
float(3) # 3.0# 特殊值轉換
float('inf') # inf
float('-inf') # -inf
float('nan') # nan# 臨界值處理
float('') # ValueError: could not convert string to float: ''
float(None) # TypeError: float() argument must be a string or a number, not 'NoneType'
float('3.14a') # ValueError: could not convert string to float: '3.14a'
1.3 str()
將對象轉換為字符串。
# 基本用法
str(123) # '123'
str(3.14) # '3.14'
str(True) # 'True'# 特殊對象轉換
str(None) # 'None'
str([1,2,3]) # '[1, 2, 3]'# 臨界值處理
str(float('inf')) # 'inf'
str(float('nan')) # 'nan'
str(object()) # '<object object at 0x...>'
1.4 bool()
將值轉換為布爾類型。
# 基本用法
bool(1) # True
bool(0) # False
bool('') # False
bool('abc') # True# 特殊值轉換
bool(None) # False
bool([]) # False
bool([0]) # True# 臨界值處理
bool(float('inf')) # True
bool(float('nan')) # True
1.5 list()
創建列表或將可迭代對象轉換為列表。
# 基本用法
list('abc') # ['a', 'b', 'c']
list((1,2,3)) # [1, 2, 3]# 空列表創建
list() # []# 臨界值處理
list(None) # TypeError: 'NoneType' object is not iterable
list(123) # TypeError: 'int' object is not iterable
list({'a':1}) # ['a'] (字典默認迭代鍵)
1.6 tuple()
創建元組或將可迭代對象轉為元組。
# 基本用法
tuple([1,2,3]) # (1, 2, 3)
tuple('abc') # ('a', 'b', 'c')# 空元組創建
tuple() # ()# 臨界值處理
tuple(None) # TypeError: 'NoneType' object is not iterable
tuple(123) # TypeError: 'int' object is not iterable
1.7 set()
創建集合或去除可迭代對象中的重復元素。
# 基本用法
set([1,2,2,3]) # {1, 2, 3}
set('aabbcc') # {'a', 'b', 'c'}# 空集合創建
set() # set()# 臨界值處理
set(None) # TypeError: 'NoneType' object is not iterable
set(123) # TypeError: 'int' object is not iterable
set([[]]) # TypeError: unhashable type: 'list'
1.8 dict()
創建字典。
# 基本用法
dict(a=1, b=2) # {'a': 1, 'b': 2}
dict([('a',1),('b',2)]) # {'a': 1, 'b': 2}# 空字典創建
dict() # {}# 臨界值處理
dict(None) # TypeError: cannot convert dictionary update sequence element #0 to a sequence
dict(123) # TypeError: cannot convert dictionary update sequence element #0 to a sequence
dict([('a',1), None]) # TypeError: cannot convert dictionary update sequence element #1 to a sequence
2. 輸入輸出函數
2.9 input()
從控制臺讀取用戶輸入的字符串。
# 基本用法
# name = input("請輸入你的名字: ") # 用戶輸入會作為字符串返回# 臨界值處理
# 輸入Ctrl+D (Unix) 或 Ctrl+Z (Windows) 會引發 EOFError
2.10 print()
將指定的對象輸出到控制臺。
# 基本用法
print('Hello', 'World') # Hello World
print(1, 2, 3, sep='-') # 1-2-3# 參數說明
# sep: 分隔符,默認為空格
# end: 結束字符,默認為換行符
# file: 輸出文件對象,默認為sys.stdout
# flush: 是否立即刷新緩沖區,默認為False# 臨界值處理
print(None) # None
print(float('inf')) # inf
print(float('nan')) # nan
3. 數學運算函數
3.11 abs()
返回一個數的絕對值。
# 基本用法
abs(-5) # 5
abs(3.14) # 3.14# 復數絕對值
abs(3+4j) # 5.0 (返回模)# 臨界值處理
abs(float('inf')) # inf
abs(float('-inf')) # inf
abs(float('nan')) # nan
3.12 max()
返回可迭代對象中的最大值。
# 基本用法
max([1, 2, 3]) # 3
max('a', 'b', 'c') # 'c'# 指定key函數
max(['apple', 'banana', 'cherry'], key=len) # 'banana'# 臨界值處理
max([]) # ValueError: max() arg is an empty sequence
max([float('nan'), 1, 2]) # nan (但比較nan的行為可能不一致)
max([None, 1, 2]) # TypeError: '>' not supported between instances of 'int' and 'NoneType'
3.13 min()
返回可迭代對象中的最小值。
# 基本用法
min([1, 2, 3]) # 1
min('a', 'b', 'c') # 'a'# 指定key函數
min(['apple', 'banana', 'cherry'], key=len) # 'apple'# 臨界值處理
min([]) # ValueError: min() arg is an empty sequence
min([float('nan'), 1, 2]) # nan (但比較nan的行為可能不一致)
min([None, 1, 2]) # TypeError: '<' not supported between instances of 'int' and 'NoneType'
3.14 sum()
對可迭代對象中的元素求和。
# 基本用法
sum([1, 2, 3]) # 6
sum([1.5, 2.5, 3]) # 7.0# 指定起始值
sum([1, 2, 3], 10) # 16# 臨界值處理
sum([]) # 0
sum(['a', 'b']) # TypeError: unsupported operand type(s) for +: 'int' and 'str'
sum([float('inf'), 1]) # inf
sum([float('nan'), 1]) # nan
3.15 round()
對浮點數進行四舍五入。
# 基本用法
round(3.14159) # 3
round(3.14159, 2) # 3.14# 銀行家舍入法(四舍六入五成雙)
round(2.5) # 2
round(3.5) # 4# 臨界值處理
round(float('inf')) # inf
round(float('nan')) # nan
round(123.456, -2) # 100.0 (負的ndigits參數)
round(123.456, 300) # 123.456 (過大ndigits參數)
4. 字符串操作函數
4.16 len()
返回對象的長度或元素個數。
# 基本用法
len('abc') # 3
len([1,2,3]) # 3
len({'a':1}) # 1# 臨界值處理
len('') # 0
len(None) # TypeError: object of type 'NoneType' has no len()
len(123) # TypeError: object of type 'int' has no len()
4.17 str.split()
以指定字符為分隔符分割字符串。
# 基本用法
'apple,banana,cherry'.split(',') # ['apple', 'banana', 'cherry']# 指定最大分割次數
'apple,banana,cherry'.split(',', 1) # ['apple', 'banana,cherry']# 臨界值處理
''.split(',') # ['']
' '.split() # [] (默認分割空白字符)
None.split() # AttributeError: 'NoneType' object has no attribute 'split'
4.18 str.join()
用指定字符串連接可迭代對象中的字符串元素。
# 基本用法
','.join(['a', 'b', 'c']) # 'a,b,c'
'-'.join('abc') # 'a-b-c'# 臨界值處理
''.join([]) # ''
','.join([1, 2, 3]) # TypeError: sequence item 0: expected str instance, int found
','.join(None) # TypeError: can only join an iterable
4.19 str.find()
在字符串中查找子串,返回首次出現的索引。
# 基本用法
'hello world'.find('world') # 6
'hello world'.find('o') # 4# 臨界值處理
'hello'.find('x') # -1 (未找到)
''.find('') # 0
'hello'.find('') # 0
'hello'.find(None) # TypeError: must be str, not NoneType
4.20 str.rfind()
從右側開始查找子串。
# 基本用法
'hello world'.rfind('o') # 7# 臨界值處理
'hello'.rfind('x') # -1
''.rfind('') # 0
'hello'.rfind('', 10) # 5 (超過字符串長度)
4.21 str.replace()
替換字符串中的指定子串。
# 基本用法
'hello world'.replace('world', 'Python') # 'hello Python'# 指定替換次數
'ababab'.replace('a', 'c', 2) # 'cbcbab'# 臨界值處理
'hello'.replace('', '-') # '-h-e-l-l-o-'
'hello'.replace('x', 'y') # 'hello' (無匹配)
'hello'.replace(None, 'y') # TypeError: replace() argument 1 must be str, not NoneType
4.22 str.strip()
去除字符串兩端的空白字符。
# 基本用法
' hello '.strip() # 'hello'
'\thello\n'.strip() # 'hello'# 指定去除字符
'xxhelloxx'.strip('x') # 'hello'# 臨界值處理
''.strip() # ''
' '.strip() # ''
None.strip() # AttributeError
4.23 str.lstrip()
去除字符串左側的空白字符。
# 基本用法
' hello '.lstrip() # 'hello '# 臨界值處理
''.lstrip() # ''
None.lstrip() # AttributeError
4.24 str.rstrip()
去除字符串右側的空白字符。
# 基本用法
' hello '.rstrip() # ' hello'# 臨界值處理
''.rstrip() # ''
None.rstrip() # AttributeError
4.25 str.upper()
將字符串轉換為大寫。
# 基本用法
'Hello'.upper() # 'HELLO'# 臨界值處理
''.upper() # ''
'123'.upper() # '123'
None.upper() # AttributeError
4.26 str.lower()
將字符串轉換為小寫。
# 基本用法
'Hello'.lower() # 'hello'# 臨界值處理
''.lower() # ''
'123'.lower() # '123'
None.lower() # AttributeError
4.27 str.title()
將每個單詞的首字母大寫。
# 基本用法
'hello world'.title() # 'Hello World'# 臨界值處理
''.title() # ''
"they're bill's".title() # "They'Re Bill'S" (注意撇號后的字母)
None.title() # AttributeError
5. 列表操作函數
5.28 list.append()
在列表末尾添加元素。
# 基本用法
lst = [1, 2]
lst.append(3) # lst變為[1, 2, 3]# 臨界值處理
lst.append(None) # lst變為[1, 2, 3, None]
lst.append(lst) # 可以添加自身(創建循環引用)
5.29 list.extend()
用可迭代對象擴展列表。
# 基本用法
lst = [1, 2]
lst.extend([3, 4]) # lst變為[1, 2, 3, 4]# 臨界值處理
lst.extend('abc') # lst變為[1, 2, 3, 4, 'a', 'b', 'c']
lst.extend(None) # TypeError: 'NoneType' object is not iterable
5.30 list.insert()
在指定位置插入元素。
# 基本用法
lst = [1, 3]
lst.insert(1, 2) # lst變為[1, 2, 3]# 臨界值處理
lst.insert(-10, 0) # 插入到最前面
lst.insert(100, 4) # 插入到最后面
lst.insert(1, None) # 可以插入None
5.31 list.remove()
移除列表中指定值的第一個匹配項。
# 基本用法
lst = [1, 2, 3, 2]
lst.remove(2) # lst變為[1, 3, 2]# 臨界值處理
lst.remove(4) # ValueError: list.remove(x): x not in list
lst.remove(None) # 如果列表中有None可以移除
5.32 list.pop()
移除并返回指定位置的元素。
# 基本用法
lst = [1, 2, 3]
lst.pop() # 返回3, lst變為[1, 2]
lst.pop(0) # 返回1, lst變為[2]# 臨界值處理
lst.pop(100) # IndexError: pop index out of range
[].pop() # IndexError: pop from empty list
5.33 list.index()
返回指定元素的索引。
# 基本用法
lst = [1, 2, 3, 2]
lst.index(2) # 1# 指定搜索范圍
lst.index(2, 2) # 3# 臨界值處理
lst.index(4) # ValueError: 4 is not in list
[].index(1) # ValueError: 1 is not in list
5.34 list.count()
返回指定元素的出現次數。
# 基本用法
lst = [1, 2, 3, 2]
lst.count(2) # 2# 臨界值處理
lst.count(4) # 0
[].count(1) # 0
lst.count(None) # 0 (除非列表中有None)
5.35 list.sort()
對列表進行原地排序。
# 基本用法
lst = [3, 1, 2]
lst.sort() # lst變為[1, 2, 3]# 指定key和reverse
lst.sort(reverse=True) # 降序排序
lst.sort(key=lambda x: -x) # 按負值排序# 臨界值處理
lst = [1, 'a', 2] # TypeError: '<' not supported between instances of 'str' and 'int'
[].sort() # 無操作
5.36 list.reverse()
反轉列表中的元素順序。
# 基本用法
lst = [1, 2, 3]
lst.reverse() # lst變為[3, 2, 1]# 臨界值處理
[].reverse() # 無操作
6. 字典操作函數
6.37 dict.keys()
返回字典的鍵視圖。
# 基本用法
d = {'a':1, 'b':2}
d.keys() # dict_keys(['a', 'b'])# 臨界值處理
{}.keys() # dict_keys([])
6.38 dict.values()
返回字典的值視圖。
# 基本用法
d = {'a':1, 'b':2}
d.values() # dict_values([1, 2])# 臨界值處理
{}.values() # dict_values([])
6.39 dict.items()
返回字典的鍵值對視圖。
# 基本用法
d = {'a':1, 'b':2}
d.items() # dict_items([('a', 1), ('b', 2)])# 臨界值處理
{}.items() # dict_items([])
6.40 dict.get()
獲取指定鍵的值,不存在則返回默認值。
# 基本用法
d = {'a':1, 'b':2}
d.get('a') # 1
d.get('c', 0) # 0# 臨界值處理
d.get('c') # None (不指定默認值時)
6.41 dict.pop()
移除并返回指定鍵的值。
# 基本用法
d = {'a':1, 'b':2}
d.pop('a') # 1, d變為{'b':2}# 指定默認值
d.pop('c', 0) # 0# 臨界值處理
d.pop('c') # KeyError: 'c'
{}.pop('a') # KeyError: 'a'
6.42 dict.popitem()
隨機移除并返回一個鍵值對。
# 基本用法
d = {'a':1, 'b':2}
d.popitem() # 可能是 ('a', 1) 或 ('b', 2)# 臨界值處理
{}.popitem() # KeyError: 'popitem(): dictionary is empty'
6.43 dict.update()
用另一個字典更新當前字典。
# 基本用法
d = {'a':1}
d.update({'b':2}) # d變為{'a':1, 'b':2}# 多種更新方式
d.update(b=3, c=4) # d變為{'a':1, 'b':3, 'c':4}# 臨界值處理
d.update(None) # TypeError: 'NoneType' object is not iterable
d.update(1) # TypeError: cannot convert dictionary update sequence element #0 to a sequence
7. 文件操作函數
7.44 open()
打開文件并返回文件對象。
# 基本用法
# f = open('file.txt', 'r') # 以只讀方式打開文件# 常用模式
# 'r' - 讀取 (默認)
# 'w' - 寫入 (會截斷文件)
# 'a' - 追加
# 'b' - 二進制模式
# '+' - 讀寫模式# 臨界值處理
# open('nonexistent.txt', 'r') # FileNotFoundError
# open('/invalid/path', 'w') # PermissionError 或其他OSError
7.45 file.read()
讀取文件內容。
# 基本用法
# with open('file.txt') as f:
# content = f.read() # 讀取全部內容# 指定讀取大小
# f.read(100) # 讀取100個字符# 臨界值處理
# f.read() 在文件關閉后調用會引發 ValueError
7.46 file.readline()
讀取文件的一行。
# 基本用法
# with open('file.txt') as f:
# line = f.readline() # 讀取一行# 臨界值處理
# 文件末尾返回空字符串 ''
7.47 file.readlines()
讀取所有行并返回列表。
# 基本用法
# with open('file.txt') as f:
# lines = f.readlines() # 返回行列表# 臨界值處理
# 空文件返回空列表 []
7.48 file.write()
將字符串寫入文件。
# 基本用法
# with open('file.txt', 'w') as f:
# f.write('hello\n') # 寫入字符串# 臨界值處理
# 只能寫入字符串,寫入其他類型會引發 TypeError
# f.write(123) # TypeError
7.49 file.close()
關閉文件。
# 基本用法
# f = open('file.txt')
# f.close()# 臨界值處理
# 多次調用close()不會報錯
# 使用with語句更安全,會自動關閉文件
8. 迭代器與生成器函數
8.50 range()
生成整數序列。
# 基本用法
list(range(5)) # [0, 1, 2, 3, 4]
list(range(1, 5)) # [1, 2, 3, 4]
list(range(1, 10, 2)) # [1, 3, 5, 7, 9]# 臨界值處理
list(range(0)) # []
list(range(1, 1)) # []
list(range(1, 5, -1)) # []
8.51 enumerate()
返回枚舉對象(索引和元素)。
# 基本用法
list(enumerate(['a', 'b', 'c'])) # [(0, 'a'), (1, 'b'), (2, 'c')]# 指定起始索引
list(enumerate(['a', 'b'], 1)) # [(1, 'a'), (2, 'b')]# 臨界值處理
list(enumerate([])) # []
list(enumerate(None)) # TypeError: 'NoneType' object is not iterable
8.52 zip()
將多個可迭代對象打包成元組。
# 基本用法
list(zip([1, 2], ['a', 'b'])) # [(1, 'a'), (2, 'b')]# 不同長度處理
list(zip([1, 2, 3], ['a', 'b'])) # [(1, 'a'), (2, 'b')]# 臨界值處理
list(zip()) # []
list(zip([], [])) # []
list(zip([1], None)) # TypeError: zip argument #2 must support iteration
9. 函數式編程函數
9.53 map()
將函數應用于可迭代對象的每個元素。
# 基本用法
list(map(str, [1, 2, 3])) # ['1', '2', '3']
list(map(lambda x: x*2, [1, 2, 3])) # [2, 4, 6]# 多個可迭代對象
list(map(lambda x,y: x+y, [1,2], [3,4])) # [4, 6]# 臨界值處理
list(map(str, [])) # []
list(map(None, [1,2])) # TypeError: 'NoneType' object is not callable
9.54 filter()
根據函數條件過濾元素。
# 基本用法
list(filter(lambda x: x>0, [-1, 0, 1, 2])) # [1, 2]# 使用None過濾假值
list(filter(None, [0, 1, False, True])) # [1, True]# 臨界值處理
list(filter(lambda x: x>0, [])) # []
9.55 reduce()
對元素進行累積計算(需從functools導入)。
from functools import reduce# 基本用法
reduce(lambda x,y: x+y, [1,2,3,4]) # 10 (((1+2)+3)+4)# 指定初始值
reduce(lambda x,y: x+y, [1,2,3], 10) # 16# 臨界值處理
reduce(lambda x,y: x+y, []) # TypeError: reduce() of empty sequence with no initial value
reduce(lambda x,y: x+y, [1]) # 1 (單元素直接返回)
10. 模塊與包函數
10.56 import
導入模塊。
# 基本用法
# import math
# math.sqrt(4)# 別名
# import numpy as np# 臨界值處理
# import nonexistent_module # ModuleNotFoundError
10.57 from…import
從模塊導入特定對象。
# 基本用法
# from math import sqrt
# sqrt(4)# 導入多個
# from math import sqrt, pi# 臨界值處理
# from math import nonexistent # ImportError: cannot import name 'nonexistent'
11. 日期時間函數
11.58 datetime.date.today()
獲取當前日期。
from datetime import date# 基本用法
# today = date.today() # 返回date對象# 臨界值處理
# 無參數,總是返回當前日期
11.59 datetime.datetime.now()
獲取當前日期和時間。
from datetime import datetime# 基本用法
# now = datetime.now() # 返回datetime對象# 指定時區
# from datetime import timezone
# datetime.now(timezone.utc)# 臨界值處理
# 無參數,總是返回當前時間
11.60 datetime.datetime.strptime()
將字符串解析為日期時間對象。
from datetime import datetime# 基本用法
# dt = datetime.strptime('2023-01-01', '%Y-%m-%d')# 臨界值處理
# datetime.strptime('invalid', '%Y') # ValueError: time data 'invalid' does not match format '%Y'
# datetime.strptime(None, '%Y') # TypeError: strptime() argument 1 must be str, not None
11.61 datetime.datetime.strftime()
將日期時間對象格式化為字符串。
from datetime import datetime# 基本用法
# now = datetime.now()
# now.strftime('%Y-%m-%d %H:%M:%S')# 臨界值處理
# datetime.strftime(None, '%Y') # AttributeError: 'NoneType' object has no attribute 'strftime'
12. 錯誤處理函數
12.62 try-except
捕獲和處理異常。
# 基本用法
try:1 / 0
except ZeroDivisionError:print("不能除以零")# 多個異常
try:# 可能出錯的代碼
except (TypeError, ValueError):# 處理多種異常
except Exception as e:# 捕獲所有異常print(f"發生錯誤: {e}")
finally:# 無論是否發生異常都會執行print("清理代碼")# 臨界值處理
# 空的try-except塊是合法但不好的做法
12.63 raise
手動拋出異常。
# 基本用法
if x < 0:raise ValueError("x不能為負數")# 重新拋出當前異常
try:1 / 0
except:print("發生錯誤")raise # 重新拋出# 臨界值處理
raise # 不在except塊中使用會引發RuntimeError
raise None # TypeError: exceptions must derive from BaseException
13. 其他常用函數
13.64 id()
返回對象的唯一標識符。
# 基本用法
x = 1
id(x) # 返回內存地址# 臨界值處理
id(None) # 返回None的id
13.65 type()
返回對象的類型。
# 基本用法
type(1) # <class 'int'>
type('a') # <class 'str'># 臨界值處理
type(None) # <class 'NoneType'>
type(type) # <class 'type'>
13.66 isinstance()
檢查對象是否是類的實例。
# 基本用法
isinstance(1, int) # True
isinstance('a', str) # True# 檢查多個類型
isinstance(1, (int, float)) # True# 臨界值處理
isinstance(1, type) # False
isinstance(int, type) # True
13.67 hasattr()
檢查對象是否有指定屬性。
# 基本用法
hasattr('abc', 'upper') # True# 臨界值處理
hasattr(None, 'x') # False
hasattr(1, 'imag') # True (int有imag屬性)
13.68 setattr()
設置對象的屬性值。
# 基本用法
class MyClass: pass
obj = MyClass()
setattr(obj, 'x', 1) # obj.x = 1# 臨界值處理
setattr(1, 'x', 1) # TypeError: 'int' object has no attribute 'x'
setattr(obj, 123, 1) # 屬性名應為字符串
13.69 getattr()
獲取對象的屬性值。
# 基本用法
getattr('abc', 'upper')() # 'ABC'# 指定默認值
getattr('abc', 'x', None) # None# 臨界值處理
getattr('abc', 123) # TypeError: attribute name must be string
13.70 delattr()
刪除對象的屬性。
# 基本用法
class MyClass: x = 1
obj = MyClass()
delattr(obj, 'x')# 臨界值處理
delattr(obj, 'x') # AttributeError: x
delattr(1, 'real') # TypeError: 'int' object has no attribute 'real'
13.71 globals()
返回全局變量的字典。
# 基本用法
globals() # 返回當前全局符號表# 臨界值處理
# 總是返回字典,即使在函數內部
13.72 locals()
返回局部變量的字典。
# 基本用法
def func():x = 1return locals()func() # {'x': 1}# 臨界值處理
# 在模塊級別,locals()和globals()相同
13.73 help()
啟動幫助系統。
# 基本用法
# help(list) # 顯示list的幫助信息# 臨界值處理
# help(None) # 顯示None的幫助信息
13.74 dir()
返回對象的屬性列表。
# 基本用法
dir(list) # 返回list的屬性和方法列表# 臨界值處理
dir() # 返回當前作用域的變量名
dir(None) # 返回None的屬性和方法列表
13.75 compile()
將字符串編譯為代碼對象。
# 基本用法
code = compile('print("hello")', 'test', 'exec')
exec(code) # 輸出hello# 臨界值處理
compile('invalid code', 'test', 'exec') # SyntaxError
compile(123, 'test', 'exec') # TypeError: expected string without null bytes
13.76 eval()
計算字符串表達式的值。
# 基本用法
eval('1 + 1') # 2# 臨界值處理
eval('import os') # SyntaxError
eval(None) # TypeError: eval() arg 1 must be a string, bytes or code object
13.77 exec()
執行字符串或代碼對象中的代碼。
# 基本用法
exec('x = 1\nprint(x)') # 輸出1# 臨界值處理
exec(None) # TypeError: exec() arg 1 must be a string, bytes or code object
13.78 hash()
返回對象的哈希值。
# 基本用法
hash('abc') # 返回哈希值# 臨界值處理
hash([]) # TypeError: unhashable type: 'list'
hash(None) # 返回None的哈希值
13.79 iter()
返回迭代器對象。
# 基本用法
it = iter([1, 2, 3])
next(it) # 1# 臨界值處理
iter(1) # TypeError: 'int' object is not iterable
iter(None) # TypeError: 'NoneType' object is not iterable
13.80 next()
獲取迭代器的下一個元素。
# 基本用法
it = iter([1, 2])
next(it) # 1# 指定默認值
next(it, 'end') # 2
next(it, 'end') # 'end'# 臨界值處理
next(it) # StopIteration
13.81 all()
檢查可迭代對象中的所有元素是否為真。
# 基本用法
all([1, 2, 3]) # True
all([1, 0, 3]) # False# 臨界值處理
all([]) # True (空可迭代對象)
all([None]) # False
13.82 any()
檢查可迭代對象中是否有任何元素為真。
# 基本用法
any([0, 1, 0]) # True
any([0, 0, 0]) # False# 臨界值處理
any([]) # False (空可迭代對象)
any([None]) # False
13.83 bytes()
創建字節對象。
# 基本用法
bytes([1, 2, 3]) # b'\x01\x02\x03'
bytes('abc', 'utf-8') # b'abc'# 臨界值處理
bytes(-1) # ValueError: negative count
bytes('abc', 'invalid') # LookupError: unknown encoding: invalid
13.84 bytearray()
創建可變的字節數組。
# 基本用法
bytearray([1, 2, 3]) # bytearray(b'\x01\x02\x03')# 臨界值處理
bytearray(-1) # ValueError: negative count
13.85 memoryview()
返回對象的內存視圖。
# 基本用法
mv = memoryview(b'abc')
mv[0] # 97# 臨界值處理
memoryview('abc') # TypeError: memoryview: a bytes-like object is required
13.86 ord()
返回字符的Unicode碼點。
# 基本用法
ord('a') # 97# 臨界值處理
ord('') # TypeError: ord() expected a character, but string of length 0 found
ord('ab') # TypeError: ord() expected a character, but string of length 2 found
13.87 chr()
根據Unicode碼點返回字符。
# 基本用法
chr(97) # 'a'# 臨界值處理
chr(-1) # ValueError: chr() arg not in range(0x110000)
chr(0x110000) # ValueError
13.88 bin()
將整數轉換為二進制字符串。
# 基本用法
bin(10) # '0b1010'# 臨界值處理
bin(3.14) # TypeError: 'float' object cannot be interpreted as an integer
bin(-10) # '-0b1010'
13.89 oct()
將整數轉換為八進制字符串。
# 基本用法
oct(8) # '0o10'# 臨界值處理
oct(3.14) # TypeError
oct(-8) # '-0o10'
13.90 hex()
將整數轉換為十六進制字符串。
# 基本用法
hex(16) # '0x10'# 臨界值處理
hex(3.14) # TypeError
hex(-16) # '-0x10'
13.91 frozenset()
創建不可變集合。
# 基本用法
fs = frozenset([1, 2, 3])# 臨界值處理
frozenset(None) # TypeError: 'NoneType' object is not iterable
13.92 super()
調用父類方法。
# 基本用法
class Parent:def method(self):print("Parent method")class Child(Parent):def method(self):super().method()print("Child method")Child().method()
# 輸出:
# Parent method
# Child method# 臨界值處理
# 不正確的使用會導致RuntimeError
13.93 property()
創建屬性描述符。
# 基本用法
class MyClass:def __init__(self):self._x = None@propertydef x(self):return self._x@x.setterdef x(self, value):self._x = valueobj = MyClass()
obj.x = 1 # 調用setter
print(obj.x) # 調用getter# 臨界值處理
# 不正確的屬性訪問會引發AttributeError
13.94 classmethod()
定義類方法。
# 基本用法
class MyClass:@classmethoddef class_method(cls):print(f"Called from {cls}")MyClass.class_method() # 通過類調用
obj = MyClass()
obj.class_method() # 通過實例調用# 臨界值處理
# 不正確的使用會導致TypeError
13.95 staticmethod()
定義靜態方法。
# 基本用法
class MyClass:@staticmethoddef static_method():print("Static method")MyClass.static_method() # 通過類調用
obj = MyClass()
obj.static_method() # 通過實例調用# 臨界值處理
# 不正確的使用會導致TypeError
13.96 len()
返回對象的長度或元素個數。
# 基本用法
len('abc') # 3
len([1,2,3]) # 3# 臨界值處理
len(123) # TypeError
len(None) # TypeError
13.97 sorted()
對可迭代對象進行排序并返回新列表。
# 基本用法
sorted([3, 1, 2]) # [1, 2, 3]# 指定key和reverse
sorted(['apple', 'banana'], key=len, reverse=True) # ['banana', 'apple']# 臨界值處理
sorted(None) # TypeError
sorted([1, 'a']) # TypeError
13.98 reversed()
返回反轉的迭代器。
# 基本用法
list(reversed([1, 2, 3])) # [3, 2, 1]# 臨界值處理
list(reversed(None)) # TypeError
list(reversed(123)) # TypeError
13.99 format()
格式化字符串。
# 基本用法
format(3.14159, '.2f') # '3.14'
"{:.2f}".format(3.14159) # '3.14'# 臨界值處理
format('abc', 123) # TypeError
13.100 vars()
返回對象的屬性字典。
# 基本用法
class MyClass: pass
obj = MyClass()
obj.x = 1
vars(obj) # {'x': 1}# 臨界值處理
vars(1) # TypeError
vars(None) # TypeError