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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.pswp.cn/bicheng/84629.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

分享在日常开发中常用的ES6知识点【面试常考】

前言 在日常的业务开发中&#xff0c;可以熟悉运用掌握的知识点快速解决问题很重要。这篇分享JS相关的知识点&#xff0c;主要就是对数据的处理。 注意&#xff1a;本篇分享的知识点&#xff0c;只是起到一个抛砖引玉的作用&#xff0c;详情的使用和更多的ES6知识点还请参考官…

CHI协议验证中的异常及边界验证

CHI协议验证中的异常及边界验证 针对 CHI 协议的错误注入工具、覆盖率衡量方法及实际项目中的投入平衡 CHI 协议作为多核系统中复杂的缓存一致性协议,验证其行为需要强大的工具和方法来执行错误注入和边界条件测试,并衡量测试覆盖率。以下详细讨论常用工具、覆盖率评估方法及…

技术专栏|LLaMA家族——模型架构

LLaMA的模型架构与GPT相同&#xff0c;采用了Transformer中的因果解码器结构&#xff0c;并在此基础上进行了多项关键改进&#xff0c;以提升训练稳定性和模型性能。LLaMA的核心架构如图 3.14 所示&#xff0c;融合了后续提出的多种优化方法&#xff0c;这些方法也在其他模型&a…

电脑插入多块移动硬盘后经常出现卡顿和蓝屏

当电脑在插入多块移动硬盘后频繁出现卡顿和蓝屏问题时&#xff0c;可能涉及硬件资源冲突、驱动兼容性、供电不足或系统设置等多方面原因。以下是逐步排查和解决方案&#xff1a; 1. 检查电源供电问题 问题原因&#xff1a;多块移动硬盘同时运行可能导致USB接口供电不足&#x…

Go 语言实现高性能 EventBus 事件总线系统(含网络通信、微服务、并发异步实战)

前言 在现代微服务与事件驱动架构&#xff08;EDA&#xff09;中&#xff0c;事件总线&#xff08;EventBus&#xff09; 是实现模块解耦与系统异步处理的关键机制。 本文将以 Go 语言为基础&#xff0c;从零构建一个高性能、可扩展的事件总线系统&#xff0c;深入讲解&#…

npm ERR! @biomejs/biome@1.9.4 postinstall: `node scripts/postinstall.js`

npm install 报错如下, npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! @biomejs/biome@1.9.4 postinstall: `node scripts/postinstall.js` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the @biomejs/biome@1.9.4 postinstall script. npm ERR! This is pro…

APMPlus × veFaaS 一键开启函数服务性能监控,让函数运行全程可观测

资料来源&#xff1a;火山引擎-开发者社区 近年来&#xff0c;无服务器架构&#xff08;Serverless&#xff09;的崛起让开发者得以从基础设施的复杂性中解放&#xff0c;专注于业务逻辑创新。但随着采用率提升&#xff0c;新的问题开始出现——函数实例的短暂生命周期、动态变…

玛哈特零件矫平机:精密制造中的平整度守护者

在精密制造、模具、冲压、钣金加工、汽车零部件、航空航天以及电子设备等众多工业领域&#xff0c;零件的平整度&#xff08;Flatness&#xff09;是一项至关重要的质量指标。微小的翘曲、扭曲或弯曲都可能导致装配困难、功能失效、外观缺陷甚至影响整机性能。为了消除零件在加…

std::make_shared简化智能指针 `std::shared_ptr` 的创建过程,并提高性能(减少内存分配次数,提高缓存命中率)

std::make_shared 是 C 标准库中的一个函数模板&#xff0c;用于简化智能指针 std::shared_ptr 的创建过程。引入 std::make_shared 的主要原因是提高代码的安全性、性能和可读性。以下是详细分析&#xff1a; 1. 安全性提升 避免显式调用 new 导致的错误 在不使用 std::make…

JDK版本如何丝滑切换

一句话总结 》》》步骤分为&#xff1a; 下载对应JDK配置环境变量 下载JDK 如何下载JDK这里不必多提&#xff0c;提出一点&#xff0c;就是多个版本的JDK最好放在一个文件夹里&#xff08;忽略我的java文件夹&#xff0c;这里都是不同的jdk版本&#xff09;&#xff1a; 配置环…

Rust 通用代码生成器:莲花,红莲尝鲜版三十六,哑数据模式图片初始化功能介绍

Rust 通用代码生成器&#xff1a;莲花&#xff0c;红莲尝鲜版三十六&#xff0c;哑数据模式图片初始化功能介绍 Rust 通用代码生成器莲花&#xff0c;红莲尝鲜版三十六。支持全线支持图片预览&#xff0c;可以直接输出带图片的哑数据模式快速原型。哑数据模式和枚举支持图片。…

45. Jump Game II

目录 题目描述 贪心 题目描述 45. Jump Game II 贪心 正向查找可到达的最大位置 时间复杂度O(n) class Solution { public:int jump(vector<int>& nums) {int n nums.size();if(n 1)return 0;int cur_cover 0;int cover 0;int res 0;for(int i 0;i < …

model.classifier 通常指模型的分类头 是什么,详细举例说明在什么部位,发挥什么作用

model.classifier 通常指模型的分类头 是什么,详细举例说明在什么部位,发挥什么作用 在深度学习模型中,分类头(Classifier Head)是指模型末端用于完成分类任务的组件,通常是一个或多个全连接层(线性层)。它的作用是将模型提取的高层语义特征映射到具体的分类标签空间。…

机器学习+城市规划第十四期:利用半参数地理加权回归来实现区域带宽不同的规划任务

机器学习城市规划第十四期&#xff1a;利用半参数地理加权回归来实现区域带宽不同的规划任务 引言 在城市规划中&#xff0c;如何根据不同地区的地理特征来制定有效的规划方案是一个关键问题。不同区域的需求和规律是不同的&#xff0c;因此我们必须考虑到地理空间的差异性。…

Kivy的ButtonBehavior学习

Kivy的ButtonBehavior学习 ButtonBehavior 简介1、主要特点2、基本用法3、主要事件4、常用属性5、方法代码示例 文档&#xff1a;https://kivy.org/doc/stable/api-kivy.uix.behaviors.button.html#kivy.uix.behaviors.button.ButtonBehavior ButtonBehavior 简介 ButtonBeha…

WPS中将在线链接转为图片

WPS中将在线链接转为图片 文章目录 WPS中将在线链接转为图片一&#xff1a;解决方案1、下载图片&#xff0c;精确匹配&#xff08;会员功能&#xff09;2、将在线链接直接转为图片 一&#xff1a;解决方案 1、下载图片&#xff0c;精确匹配&#xff08;会员功能&#xff09; …

API:解锁数字化协作的钥匙及开放实现路径深度剖析

API:解锁数字化协作的钥匙及开放实现路径深度剖析 一、API 的概念与本质 (一)定义与基本原理 API(Application Programming Interface,应用程序编程接口)是一组定义、协议和工具,用于构建和集成软件应用程序。它如同一个精心设计的合约,详细规定了软件组件之间相互交…

Azure 虚拟机端口资源:专用 IP 和公共 IP Azure Machine Learning 计算实例BUG

## 报错无解 找不到Azure ML 计算实例关联的 NSG .env 文件和 ufw status&#xff1a; .env 文件中 EXPOSE_NGINX_PORT8080 是正确的&#xff0c;它告诉 docker-compose.yaml 将 Nginx 暴露在宿主机的 8080 端口。 sudo ufw status 显示 Status: inactive&#xff0c;意味着宿…

深入理解Python协程:async def、async for、await、yield详解

前言 在现代编程中&#xff0c;异步编程已成为提高程序效率和性能的重要方式。 Python 作为一种流行的编程语言&#xff0c;自然也提供了强大的异步编程支持。 本文将详细介绍 Python 中的协程&#xff0c;以及 async def、async for、await 和 yield 等关键字的使用。 协程简介…

基于功能基团的3D分子生成扩散模型 - D3FG 评测

D3FG 是一个在口袋中基于功能团的3D分子生成扩散模型。与通常分子生成模型直接生成分子坐标和原子类型不同&#xff0c;D3FG 将分子分解为两类组成部分&#xff1a;官能团和连接体&#xff0c;然后使用扩散生成模型学习这些组成部分的类型和几何分布。 一、背景介绍 D3FG 来源…