云计算百科
云计算领域专业知识百科平台

Python 100个常用函数全面解析

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 = 1
return 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

@property
def x(self):
return self._x

@x.setter
def x(self, value):
self._x = value

obj = MyClass()
obj.x = 1 # 调用setter
print(obj.x) # 调用getter

# 临界值处理
# 不正确的属性访问会引发AttributeError

13.94 classmethod()

定义类方法。

# 基本用法
class MyClass:
@classmethod
def class_method(cls):
print(f"Called from {cls}")

MyClass.class_method() # 通过类调用
obj = MyClass()
obj.class_method() # 通过实例调用

# 临界值处理
# 不正确的使用会导致TypeError

13.95 staticmethod()

定义静态方法。

# 基本用法
class MyClass:
@staticmethod
def 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

赞(0)
未经允许不得转载:网硕互联帮助中心 » Python 100个常用函数全面解析
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!