函数使用(一)
前言
- 这一篇是查表用的笔记:每个大类先用清单把常用函数过一遍,再给一个把清单里所有函数都用上的完整示例,跑一遍就能对上号。
- 示例输出都是本机 Python 3.13.9 实跑的结果;随机数固定了种子,时间戳这类只打印稳定结论,不会每次跑都对不上。
- 清单里标了「返回 None」「原地」「浅拷贝」「抛什么异常」这几类,是最容易踩的地方,示例里都有对应演示。
常用函数
-
内置函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23print:打印、输出
input:获取用户输入
abs:求绝对值
type:查看值的类型
chr:码点 → 字符,不只 ASCII:chr(0x4E2D) 得 '中';越界抛 ValueError
ord:字符 → 码点(Unicode,不是 ASCII 码),ord('中') 得 20013;与 chr 互逆
id:对象的唯一标识,CPython 里就是内存地址;只能同一时刻比较,别拿它做业务判断
len:元素个数;字符串按码点计数,len('hello你好') 得 7
range:整数序列对象(不是生成器),支持 len / 索引 / 切片,`x in range(...)` 是 O(1)
enumerate:枚举成 (下标, 元素),默认从 0 起,可给 start
类型转换 / 类型本身(同一批名字既是函数也是类型,千万别拿来当变量名):
int float complex bool str bytes bytearray
list tuple set frozenset dict
sum:求和(可给 start 初值)
max / min:最大最小值,支持 key 参数
pow:求幂,pow(2, 3) 等价 2**3;三参数 pow(2, 10, 1000) 是带模幂,得 24
divmod:一次拿到商和余数,divmod(10, 3) 得 (3, 1)
round:可指定保留位数,但它是**银行家舍入**(四舍六入五成双):
round(0.5) 得 0、round(1.5) 和 round(2.5) 都得 2;
还受浮点表示影响,round(2.675, 2) 得 2.67 而不是 2.68
hex / oct / bin:转成带前缀的**字符串**,hex(16) 得 '0x10'、oct(16) 得 '0o20'、bin(16) 得 '0b10000'还有一批同样常用、别只记上面那些:
1
2
3
4
5
6
7
8
9
10zip:多个可迭代对象并成元组序列,长度以最短的为准
map / filter:对每个元素做变换 / 筛选,都返回惰性迭代器
sorted / reversed:返回排好序 / 反序的**新**对象(列表的 sort / reverse 是原地)
all / any:全真 / 有真;注意 all([]) 是 True、any([]) 是 False
isinstance / issubclass:类型判断,优先用它而不是比较 __name__
repr:对象的「可打印」形式(字符串会带引号),调试好用
hash:对象的哈希值,只对可哈希对象有效(列表会 TypeError)
callable / getattr / setattr / hasattr:把函数当对象时用得上
open:读写文件;format / f-string:字符串格式化
dir / help:看对象有什么、查文档整体示例:把上面清单里的函数全用一遍
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60import builtins
import pydoc
# 输入 / 输出:input 拿到的一律是字符串
builtins.input = lambda prompt='': '42' # 演示时假装用户敲了 42
user = input('请输入一个数:')
print('input:', repr(user), '-> int:', int(user))
print('print 的 sep/end:', 'a', 'b', 'c', sep='|', end='\n')
# 数值
print('abs:', abs(-7))
print('pow:', pow(2, 3), '等价写法:', 2 ** 3, '带模:', pow(2, 10, 1000))
print('divmod:', divmod(10, 3))
print('sum:', sum([1, 2, 3]), '带初值:', sum([1, 2], 10))
print('max/min:', max([1, 9, 3]), min([1, 9, 3]), '按 key:', max(['a', 'bbb', 'cc'], key=len))
print('round 银行家舍入:', round(0.5), round(2.5), '受浮点影响:', round(2.675, 2))
# 类型与转换
print('type:', type(7).__name__, type(7.0).__name__, type('a').__name__, type([]).__name__)
print('int/float/complex:', int('42'), int(3.9), float('3.5'), complex(1, 2))
print('bool:', bool(0), bool(''), bool([]), bool([0]))
print('str/bytes/bytearray:', str(12), repr('中'.encode('utf-8')), bytearray(b'\x01\x02'))
print('list/tuple/set/dict:', list('ab'), tuple([1, 2]), set([1, 1, 2]), dict(a=1, b=2))
print('frozenset 可哈希、能进集合:', {frozenset({1}), frozenset({1})})
# 序列与迭代
print('len:', len('hello你好'), len([1, 2, 3]))
print('range:', list(range(3)), list(range(1, 6, 2)), '成员判断 O(1):', 5 in range(10))
print('enumerate:', list(enumerate('ab')), '带 start:', list(enumerate('ab', start=1)))
print('zip 以最短为准:', list(zip([1, 2], 'abc')))
print('map:', list(map(str, [1, 2])), 'filter 去假值:', list(filter(None, [0, 1, '', 2])))
print('sorted:', sorted([3, 1, 2]), sorted(['b', 'aa'], key=len), 'reversed:', list(reversed([1, 2])))
# 进制与字符
print('hex/oct/bin:', hex(16), oct(16), bin(16))
print('chr/ord 是 Unicode 码点:', chr(0x4E2D), ord('中'))
# 判定与反射
print('all/any:', all([1, 2]), '空真:', all([]), any([0, '']), any([]))
print('isinstance/issubclass:', isinstance([], list), issubclass(bool, int))
print('repr:', repr('a'), repr([1, 'a']))
print('hash 只对可哈希对象:', isinstance(hash((1, 2)), int))
def f():
pass
print('callable:', callable(f), callable(1))
class C:
x = 1
c = C()
print('hasattr/getattr/setattr:', hasattr(c, 'x'), getattr(c, 'x'), getattr(c, 'z', '默认'),
setattr(c, 'y', 2) or c.y)
print('dir 挑一个名字:', [n for n in dir([]) if n.startswith('append')])
print('help 的脚本版(pydoc)里有 int 说明:', 'integer' in pydoc.render_doc(int).lower())
# 文件与格式化
with open('demo.txt', 'w', encoding='utf-8') as fp:
fp.write('第一行\n第二行\n')
with open('demo.txt', encoding='utf-8') as fp:
print('open 写后读回:', fp.read().split())
print('format:', format(3.14159, '.2f'), '{}-{}'.format('a', 'b'), f"{'x':>6}|{1 + 1}")
print('id 只在同一时刻可比:', id(c) == id(c))实跑输出:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33input: '42' -> int: 42
print 的 sep/end:|a|b|c
abs: 7
pow: 8 等价写法: 8 带模: 24
divmod: (3, 1)
sum: 6 带初值: 13
max/min: 9 1 按 key: bbb
round 银行家舍入: 0 2 受浮点影响: 2.67
type: int float str list
int/float/complex: 42 3 3.5 (1+2j)
bool: False False False True
str/bytes/bytearray: 12 b'\xe4\xb8\xad' bytearray(b'\x01\x02')
list/tuple/set/dict: ['a', 'b'] (1, 2) {1, 2} {'a': 1, 'b': 2}
frozenset 可哈希、能进集合: {frozenset({1})}
len: 7 3
range: [0, 1, 2] [1, 3, 5] 成员判断 O(1): True
enumerate: [(0, 'a'), (1, 'b')] 带 start: [(1, 'a'), (2, 'b')]
zip 以最短为准: [(1, 'a'), (2, 'b')]
map: ['1', '2'] filter 去假值: [1, 2]
sorted: [1, 2, 3] ['b', 'aa'] reversed: [2, 1]
hex/oct/bin: 0x10 0o20 0b10000
chr/ord 是 Unicode 码点: 中 20013
all/any: True 空真: True False False
isinstance/issubclass: True True
repr: 'a' [1, 'a']
hash 只对可哈希对象: True
callable: True False
hasattr/getattr/setattr: True 1 默认 2
dir 挑一个名字: ['append']
help 的脚本版(pydoc)里有 int 说明: True
open 写后读回: ['第一行', '第二行']
format: 3.14 a-b x|2
id 只在同一时刻可比: True -
常见的模块函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39random:
randint:随机整数,参数是起止,**闭区间** [a, b]
randrange:随机整数,**半开区间** [start, stop),和 range 一样
random:[0, 1) 的随机浮点数(能取到 0,取不到 1)
uniform:指定范围的随机浮点数,端点可能被取到
choice:从序列里随机取**一个**元素
sample:无放回抽样,返回长度为 k 的列表;k 大于总体数会 ValueError
choices:有放回抽样,可指定权重 weights,返回列表,**长度可以超过总体**
shuffle:原地打乱列表,返回 None(别写成 x = shuffle(x),那会把 x 变成 None)
seed:设定随机种子,同一种子结果可复现
time:
sleep:睡眠指定秒数,可以是小数
time:当前时间戳(秒,浮点)
perf_counter:高精度计时,量代码耗时用它而不是 time()
ctime:时间戳转可读字符串
gmtime / localtime:转 struct_time;strftime / strptime:格式化 / 解析
math:
e:自然对数 2.718281828459045
pi:圆周率 3.141592653589793
tau:2π
ceil / floor:向上 / 向下取整,返回 int
trunc:截断小数部分(朝 0 方向),trunc(-2.9) 得 -2
sqrt:平方根(返回浮点);isqrt:整数平方根,isqrt(17) 得 4
pow / exp / log / log2 / log10:幂与自然对数、常用对数
sin / cos / tan 等:参数是弧度
degrees / radians:弧度 ↔ 度
fabs:绝对值(浮点);gcd:最大公约数;factorial:阶乘
prod:连乘,math.prod([1, 2, 3, 4]) 得 24(3.8+)
inf / nan / isinf / isnan:无穷与「非数」
sys:
argv:命令行参数列表,argv[0] 是脚本名;参数一多改用 argparse 解析
path:模块搜索路径
getrecursionlimit / setrecursionlimit:递归深度上限
os:
system:执行系统命令,如 os.system('cls') 清屏;
**返回的是退出状态码**(0 表示成功),拿不到命令输出,
要输出请用 subprocess.check_output
getcwd / chdir / listdir / mkdir / remove / rename:目录与文件操作
sep / name / environ:路径分隔符、平台标识、环境变量整体示例:把上面清单里的函数全用一遍
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62import math, os, random, sys, time
# random:先固定种子,输出才可复现
random.seed(1)
print('randint 闭区间[1,6]:', random.randint(1, 6), ' randrange 半开[1,6):', random.randrange(1, 6))
print('random 在[0,1):', round(random.random(), 3), ' uniform(1,5):', round(random.uniform(1, 5), 3))
pool = ['a', 'b', 'c', 'd']
print('choice 取一个:', random.choice(pool))
print('sample 无放回 k=2:', random.sample(pool, 2), ' k 超过总体会 ValueError:', len(pool))
print('choices 有放回 k=6:', random.choices(pool, k=6))
print('choices 带权重也能跑:', len(random.choices(pool, weights=[1, 1, 1, 10], k=5)))
cards = [1, 2, 3, 4, 5]
print('shuffle 返回 None:', random.shuffle(cards), ' 但原地打乱了:', sorted(cards) == cards)
# time
t0 = time.time()
time.sleep(0.2)
print('sleep 生效:', time.time() - t0 >= 0.2)
start = time.perf_counter()
sum(range(1000))
print('perf_counter 量耗时:', time.perf_counter() - start >= 0)
print('ctime 形如:', len(time.ctime(t0).split()) == 5)
print('strftime:', time.strftime('%Y-%m-%d %H:%M', time.localtime(t0)))
print('strptime 解析回来:', time.strptime('2020-01-02', '%Y-%m-%d').tm_year)
print('gmtime 用 UTC:', time.gmtime(0).tm_year, time.localtime(0).tm_year)
# math
print('e/pi/tau:', round(math.e, 5), round(math.pi, 5), round(math.tau, 5))
print('ceil/floor/trunc:', math.ceil(2.1), math.floor(2.9), math.trunc(-2.9))
print('sqrt/isqrt:', math.sqrt(9), math.isqrt(17))
print('pow/exp/log:', math.pow(2, 3), round(math.exp(1), 5), round(math.log(math.e), 5),
math.log2(8), round(math.log10(1000), 9))
print('三角(参数是弧度):', round(math.sin(math.pi / 2), 5), round(math.cos(0), 5), round(math.tan(0), 5))
print('degrees/radians:', round(math.degrees(math.pi), 5), round(math.radians(180), 5))
print('fabs/gcd/factorial/prod:', math.fabs(-3), math.gcd(12, 18), math.factorial(5), math.prod([1, 2, 3, 4]))
print('isinf/isnan:', math.isinf(math.inf), math.isnan(float('nan')))
# sys
print('argv 第一项是脚本名:', sys.argv[0].endswith('.py'))
print('path 是列表:', isinstance(sys.path, list))
old = sys.getrecursionlimit()
sys.setrecursionlimit(1200)
print('递归上限可读写:', sys.getrecursionlimit() == 1200)
sys.setrecursionlimit(old)
# os
print('name/sep:', os.name in ('nt', 'posix'), repr(os.sep))
print('getcwd 是绝对路径:', os.path.isabs(os.getcwd()))
os.mkdir('tmp_dir')
os.chdir('tmp_dir')
with open('a.txt', 'w') as fp:
fp.write('x')
print('listdir:', os.listdir('.'))
os.rename('a.txt', 'b.txt')
print('rename 后:', os.listdir('.'))
os.remove('b.txt')
print('remove 后:', os.listdir('.'))
os.chdir('..')
os.rmdir('tmp_dir')
print('rmdir 清理:', 'tmp_dir' not in os.listdir('.'))
print('system 返回退出码:', os.system('exit 0' if os.name == 'posix' else 'cmd /c exit 0'))
print('environ 可读,条数 > 0:', len(os.environ) > 0)实跑输出:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32randint 闭区间[1,6]: 2 randrange 半开[1,6): 5
random 在[0,1): 0.847 uniform(1,5): 4.055
choice 取一个: c
sample 无放回 k=2: ['a', 'b'] k 超过总体会 ValueError: 4
choices 有放回 k=6: ['d', 'b', 'b', 'a', 'b', 'd']
choices 带权重也能跑: 5
shuffle 返回 None: None 但原地打乱了: False
sleep 生效: True
perf_counter 量耗时: True
ctime 形如: True
strftime: 2026-10-31 23:38
strptime 解析回来: 2020
gmtime 用 UTC: 1970 1970
e/pi/tau: 2.71828 3.14159 6.28319
ceil/floor/trunc: 3 2 -2
sqrt/isqrt: 3.0 4
pow/exp/log: 8.0 2.71828 1.0 3.0 3.0
三角(参数是弧度): 1.0 1.0 0.0
degrees/radians: 180.0 3.14159
fabs/gcd/factorial/prod: 3.0 6 120 24
isinf/isnan: True True
argv 第一项是脚本名: True
path 是列表: True
递归上限可读写: True
name/sep: True '\\'
getcwd 是绝对路径: True
listdir: ['a.txt']
rename 后: ['b.txt']
remove 后: []
rmdir 清理: True
system 返回退出码: 0
environ 可读,条数 > 0: True -
字符串函数
字符串不可变:下面这些方法全都返回新串,不存在原地修改。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44join:用分隔符把可迭代对象拼成字符串
l = ['泉眼无声惜细流', '树阴照水爱晴柔', '小荷才露尖尖角', '早有蜻蜓立上头']
print(','.join(l))
# 元素必须都是 str,混进数字直接 TypeError:','.join(['a', 1])
# 批量拼接用 join 而不是循环 +=:字符串不可变,+= 整体是 O(n²)
字符填充:
ljust(width[, fillchar]):左对齐,右边填充
rjust(width[, fillchar]):右对齐,左边填充
center(width[, fillchar]):居中,两边填充
zfill(width):左边补 '0',符号位保持在最前:'-12'.zfill(5) 得 '-0012'
strip([chars]):去掉两边的字符,不传参数时去空白(空格、\n、\t 等)
# 注意 chars 是「字符集合」而不是后缀:'mississippi'.strip('mis') 得 'pp'
lstrip / rstrip:只去左边 / 只去右边
removeprefix / removesuffix:去掉前缀 / 后缀(3.9+),这才是「按整串删」
replace(old, new[, count]):替换,给了 count 就只换前 count 个
split([sep][, maxsplit]):不传 sep 时按任意空白切分并丢掉空串;给了 sep 才按它切
rsplit:从右边开始切,配合 maxsplit 时保留的是左边部分
splitlines:按换行切,keepends=True 可保留换行符
partition(sep):按第一个 sep 切成 (前, sep, 后) 三段
find(sub[, start[, end]]):返回第一次出现的下标,找不到返回 -1
rfind:从右边找,但返回的下标仍是从左数
index / rindex:和 find 一样,只是找不到时抛 ValueError 而不是返回 -1
count(sub):统计出现次数
upper / lower:全大写 / 全小写
swapcase:大小写互换
capitalize:首字符大写,**其余字母会被转成小写**:'hELLO'.capitalize() 得 'Hello'
title:每个单词首字母大写
casefold:比 lower 更彻底的大小写折叠,做「忽略大小写比较」用它('ß'.casefold() 得 'ss')
startswith / endswith:是否以…开头 / 结尾,参数可以是元组(满足其一即可)
maketrans + translate:建字符映射表后批量替换(删字符就把值映射成 None)
expandtabs(tabsize=8):把 \t 展开成空格
判断类(找不到都返回 False,不抛异常):
isalpha:是否全是字母(中文也算字母,'中'.isalpha() 为 True)
isdigit / isdecimal / isnumeric:范围依次变大,isdecimal ⊂ isdigit ⊂ isnumeric
'2'.isdigit() / .isdecimal() / .isnumeric() 都是 True
'²'.isdigit() 为 True,但 .isdecimal() 为 False
'零'.isnumeric() 为 True,但 .isdigit() 为 False
isalnum:是否是字母或数字
isspace / istitle / isidentifier / isprintable整体示例:把上面清单里的函数全用一遍
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39lines = ['泉眼无声惜细流', '树阴照水爱晴柔', '小荷才露尖尖角', '早有蜻蜓立上头']
print('join:', ','.join(lines))
print('join 混数字会 TypeError:', all(isinstance(x, str) for x in lines))
s = ' Py thon '
print('ljust/rjust/center:', repr('a'.ljust(4)), repr('a'.rjust(4)), repr('a'.center(5)))
print('zfill 保住符号:', '-12'.zfill(5))
print('strip 家族:', repr(s.strip()), repr(s.lstrip()), repr(s.rstrip()))
print('strip 参数是字符集合:', 'mississippi'.strip('mis'))
print('removeprefix/removesuffix:', 'a.txt'.removeprefix('a.'), 'a.txt'.removesuffix('.txt'))
print('replace 限次:', 'aaaa'.replace('a', 'b', 2))
print('split 不传参按空白:', ' a b '.split(), ' 传参保留空串:', 'a,,b'.split(','))
print('split maxsplit:', 'a,b,c'.split(',', 1), 'rsplit maxsplit:', 'a,b,c'.rsplit(',', 1))
print('splitlines:', 'a\nb\nc'.splitlines())
print('partition:', 'a=b=c'.partition('='))
t = 'hello world hello'
print('find/rfind:', t.find('world'), t.rfind('l'), '找不到返回 -1:', t.find('zzz'))
print('index/rindex 找不到抛 ValueError:', t.index('world'), t.rindex('l'))
print('count:', t.count('l'))
print('upper/lower/swapcase:', 'aB'.upper(), 'aB'.lower(), 'aB'.swapcase())
print('capitalize 会压小其余:', 'hELLO world'.capitalize())
print('title:', 'hello world'.title())
print('casefold 更彻底:', 'ß'.casefold(), 'STRASSE'.casefold() == 'strasse'.casefold())
print('startswith/endswith 可用元组:', 'a.txt'.startswith(('a', 'b')), 'a.txt'.endswith('.txt'))
table = str.maketrans('ae', '12')
print('maketrans + translate:', 'apple'.translate(table), ' 删字符:', 'apple'.translate(str.maketrans('', '', 'p')))
print('expandtabs:', repr('a\tb'.expandtabs(4)))
print('isalpha 认中文:', '中'.isalpha(), 'isalnum:', 'a1'.isalnum(), 'isspace:', ' \t'.isspace())
print('istitle:', 'Hello World'.istitle(), 'isidentifier:', 'var_1'.isidentifier(), 'isprintable:', 'a '.isprintable())
print('isdigit/isdecimal/isnumeric 三档:', '²'.isdigit(), '²'.isdecimal(), '零'.isnumeric(), '零'.isdigit())
print('字符串不可变:方法都返回新串')
s2 = 'abc'
s2.upper()
print(' 原串不变:', s2)实跑输出:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27join: 泉眼无声惜细流,树阴照水爱晴柔,小荷才露尖尖角,早有蜻蜓立上头
join 混数字会 TypeError: True
ljust/rjust/center: 'a ' ' a' ' a '
zfill 保住符号: -0012
strip 家族: 'Py thon' 'Py thon ' ' Py thon'
strip 参数是字符集合: pp
removeprefix/removesuffix: txt a
replace 限次: bbaa
split 不传参按空白: ['a', 'b'] 传参保留空串: ['a', '', 'b']
split maxsplit: ['a', 'b,c'] rsplit maxsplit: ['a,b', 'c']
splitlines: ['a', 'b', 'c']
partition: ('a', '=', 'b=c')
find/rfind: 6 15 找不到返回 -1: -1
index/rindex 找不到抛 ValueError: 6 15
count: 5
upper/lower/swapcase: AB ab Ab
capitalize 会压小其余: Hello world
title: Hello World
casefold 更彻底: ss True
startswith/endswith 可用元组: True True
maketrans + translate: 1ppl2 删字符: ale
expandtabs: 'a b'
isalpha 认中文: True isalnum: True isspace: True
istitle: True isidentifier: True isprintable: True
isdigit/isdecimal/isnumeric 三档: True False True False
字符串不可变:方法都返回新串
原串不变: abc -
列表函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16append(x):把 x 作为**一个元素**追加到末尾
extend(iterable):把可迭代对象**逐个**追加:[1,2].extend([3,4]) 得 [1,2,3,4],
而 append([3,4]) 得 [1,2,[3,4]]
insert(i, x):在下标 i 处插入(往头部插是 O(n),频繁两头插用 collections.deque)
remove(x):删除第一个值为 x 的元素;没有该值抛 ValueError
pop([i=-1]):删除并**返回**被删元素,默认最后一个;空列表 pop 抛 IndexError
del lt[i]:按下标删除,不返回;del lt[:] 与 lt.clear() 都是原地清空
index(x):第一个值为 x 的下标,没有抛 ValueError(区别于返回 -1 的 str.find)
count(x):统计出现次数
sort(*, key=None, reverse=False):**原地**排序,返回 None
reverse():**原地**逆序,返回 None
→ 想要新列表用内置函数 sorted() / reversed();
→ 常见错误:lt = lt.sort() 会把 lt 变成 None
copy():**浅拷贝**,只复制最外层,嵌套的内层仍然共享
clear():清空另外这几个不是方法但天天配着用:
len(lt)、x in lt(O(n))、lt + lt2、lt * n、切片与切片赋值。整体示例:把上面清单里的函数全用一遍
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45lt = [3, 1, 2]
lt.append(4)
print('append 整体加一个:', lt)
lt.append([9, 9])
print(' append 列表是塞进一个元素:', lt)
lt.pop() # 收回上面那个嵌套
lt.extend([5, 6])
print('extend 逐个加:', lt)
lt.insert(0, 0)
print('insert 按下标插:', lt)
print('count:', lt.count(2), 'index:', lt.index(2), ' 找不到抛 ValueError:', 99 not in lt)
print('in 是 O(n) 线性扫描:', 5 in lt)
print('pop 默认弹尾并返回:', lt.pop(), ' 指定下标:', lt.pop(0))
lt.remove(3)
print('remove 按值删第一个:', lt)
del lt[0]
print('del 按下标删:', lt)
lt.sort()
print('sort 原地,返回 None:', sorted(lt) == lt)
lt.sort(reverse=True)
print('sort 带 reverse:', lt)
lt.sort(key=lambda x: -x)
print('sort 带 key:', lt)
print('sorted 返回新列表:', sorted([2, 1]), ' 原列表不动:', lt == sorted(lt, reverse=True))
lt.reverse()
print('reverse 原地:', lt)
print('reversed 返回迭代器:', list(reversed(lt)))
shallow = lt.copy()
nested = [[1], 2]
sh2 = nested.copy()
sh2[0].append(9)
print('copy 是浅拷贝,内层仍共享:', nested)
import copy as cp
deep = cp.deepcopy(nested)
nested[0].append(8)
print('deepcopy 才彻底独立:', deep, '原对象:', nested)
print('拼接与重复(都是新列表):', [1] + [2], [1] * 3)
print('切片:', lt[1:3], ' 切片赋值可批量增删:', (lambda x: (x.__setitem__(slice(0, 2), []), x)[1])([1, 2, 3]))
lt.clear()
print('clear 清空:', lt, ' len:', len(lt))实跑输出:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20append 整体加一个: [3, 1, 2, 4]
append 列表是塞进一个元素: [3, 1, 2, 4, [9, 9]]
extend 逐个加: [3, 1, 2, 4, 5, 6]
insert 按下标插: [0, 3, 1, 2, 4, 5, 6]
count: 1 index: 3 找不到抛 ValueError: True
in 是 O(n) 线性扫描: True
pop 默认弹尾并返回: 6 指定下标: 0
remove 按值删第一个: [1, 2, 4, 5]
del 按下标删: [2, 4, 5]
sort 原地,返回 None: True
sort 带 reverse: [5, 4, 2]
sort 带 key: [5, 4, 2]
sorted 返回新列表: [1, 2] 原列表不动: True
reverse 原地: [2, 4, 5]
reversed 返回迭代器: [5, 4, 2]
copy 是浅拷贝,内层仍共享: [[1, 9], 2]
deepcopy 才彻底独立: [[1, 9], 2] 原对象: [[1, 9, 8], 2]
拼接与重复(都是新列表): [1, 2] [1, 1, 1]
切片: [4, 5] 切片赋值可批量增删: [3]
clear 清空: [] len: 0 -
字典
1
2
3
4
5
6
7
8
9
10
11keys / values / items:返回**视图对象**(不是列表),字典一变视图跟着变,
可以直接 for 循环、做集合运算(d.keys() & other.keys());要快照就 list(...)
get(key, default=None):取值,键不存在返回 default,不抛异常
setdefault(key, default):取值;键不存在时**顺便写入** default 再返回它
pop(key[, default]):删除并返回该键的值;键不存在时给了 default 就返回它,否则 KeyError
popitem():删除并返回一对键值;3.7 起是**最后插入**的那对(LIFO)
update(other):把 other 的键值对合进来,同名键被覆盖
3.9+ 还可以直接写 d1 | d2(要原地更新用 |=)
clear():清空
copy():浅拷贝
fromkeys(seq, value):批量建字典;value 是可变对象时所有键共享同一个,改一个全变x in d判的是键,不是值;要判值得写v in d.values()。整体示例:把上面清单里的函数全用一遍
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28d = {'a': 1, 'b': 2}
print('keys/values/items 是视图:', list(d.keys()), list(d.values()), list(d.items()))
d['c'] = 3
print('视图跟着变(不用重新取):', len(d.items()))
print('视图能做集合运算:', d.keys() & {'a', 'x'})
print('get 缺失给默认:', d.get('zz', '没有'), ' 不带默认返回 None:', d.get('zz'))
print('setdefault 缺失时顺便写入:', d.setdefault('d', 4), ' 现在有这个键:', 'd' in d)
print('in 判键不判值:', 'a' in d, 1 in d)
print('pop 删除并返回值:', d.pop('d'), ' 带 default 不报错:', d.pop('zz', '无'), ' 不带则 KeyError:', 'd' in d)
print('popitem 弹最后插入的一对:', d.popitem())
d.update({'x': 9})
print('update 合入:', d)
d.update({'x': 10})
print('同名键被覆盖:', d['x'])
print('3.9 的 | 合并:', {'a': 1} | {'b': 2}, ' 同名取右:', {'a': 1} | {'a': 2})
shared = dict.fromkeys(['k1', 'k2'], 0)
print('fromkeys:', shared)
bad = dict.fromkeys(['k1', 'k2'], [])
bad['k1'].append(1)
print('fromkeys 默认值是可变对象时全部共享:', bad)
snap = d.copy()
d['y'] = 1
print('copy 后原字典不受影响:', 'y' in snap, 'y' in d)
d.clear()
print('clear:', d, ' len:', len(d))实跑输出:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15keys/values/items 是视图: ['a', 'b'] [1, 2] [('a', 1), ('b', 2)]
视图跟着变(不用重新取): 3
视图能做集合运算: {'a'}
get 缺失给默认: 没有 不带默认返回 None: None
setdefault 缺失时顺便写入: 4 现在有这个键: True
in 判键不判值: True False
pop 删除并返回值: 4 带 default 不报错: 无 不带则 KeyError: False
popitem 弹最后插入的一对: ('c', 3)
update 合入: {'a': 1, 'b': 2, 'x': 9}
同名键被覆盖: 10
3.9 的 | 合并: {'a': 1, 'b': 2} 同名取右: {'a': 2}
fromkeys: {'k1': 0, 'k2': 0}
fromkeys 默认值是可变对象时全部共享: {'k1': [1], 'k2': [1]}
copy 后原字典不受影响: False True
clear: {} len: 0 -
集合
1
2
3
4
5
6
7
8
9
10
11
12add(x):加一个元素(元素必须可哈希)
update(iterable):逐个加入多个元素
remove(x):删除指定元素,不存在抛 KeyError
discard(x):删除指定元素,不存在也不报错
pop():弹出**任意**一个元素——顺序由哈希表布局决定,不保证插入顺序(也不是真随机);空集合 pop 抛 KeyError
clear():清空
copy():浅拷贝
交并差:intersection / union / difference / symmetric_difference
对应运算符 & | - ^;原地版本都带 _update 后缀,且**返回 None**
关系判断:issubset(<=) / issuperset(>=) / isdisjoint
注意 intersection_update 之类别写成 x = a.intersection_update(b),那是 None集合是哈希表,
x in s、add、remove平均 O(1),所以「判存在 / 去重」优先想到它,别拿列表做 O(n) 的线性扫描;代价是不保证顺序、元素必须可哈希。不可变版本是frozenset。整体示例:把上面清单里的函数全用一遍
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33s = {1, 2, 3}
s.add(4)
print('add:', sorted(s))
s.add(2)
print('重复元素不会进集合:', len(s))
s.update([4, 5, 6])
print('update 逐个加:', sorted(s))
print('元素必须可哈希,列表进不去:', isinstance(frozenset({1}), object))
s.remove(6)
print('remove 删指定元素:', sorted(s), ' 不存在会 KeyError:', 6 not in s)
s.discard(99)
print('discard 不存在也不报错:', sorted(s))
one = s.pop()
print('pop 弹出任意一个(不保证插入顺序):', one in {1, 2, 3, 4, 5}, ' 少了一个:', len(s))
a, b = {1, 2, 3}, {2, 3, 4}
print('交集 intersection / &:', a & b, a.intersection(b))
print('并集 union / |:', a | b, a.union(b))
print('差集 difference / -:', a - b, a.difference(b))
print('对称差 symmetric_difference / ^:', a ^ b, a.symmetric_difference(b))
a.intersection_update(b)
print('原地版改自己、返回 None:', sorted(a))
a = {1, 2, 3}
a.difference_update({1})
print('difference_update:', sorted(a))
print('issubset / 子集:', {1} <= a, a.issubset({1, 2, 3, 9}))
print('issuperset / 超集:', a >= {1}, {1, 2}.issuperset({1}))
print('isdisjoint / 无交集:', a.isdisjoint({100}), {1}.isdisjoint({2}))
print('len 与 in(哈希平均 O(1)):', len(a), 2 in a)
print('frozenset 可当字典的键:', {frozenset({1, 2}): '值'}[frozenset({1, 2})])
a.clear()
print('clear:', a, ' 空集合 pop 会 KeyError:', len(a) == 0)实跑输出:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19add: [1, 2, 3, 4]
重复元素不会进集合: 4
update 逐个加: [1, 2, 3, 4, 5, 6]
元素必须可哈希,列表进不去: True
remove 删指定元素: [1, 2, 3, 4, 5] 不存在会 KeyError: True
discard 不存在也不报错: [1, 2, 3, 4, 5]
pop 弹出任意一个(不保证插入顺序): True 少了一个: 4
交集 intersection / &: {2, 3} {2, 3}
并集 union / |: {1, 2, 3, 4} {1, 2, 3, 4}
差集 difference / -: {1} {1}
对称差 symmetric_difference / ^: {1, 4} {1, 4}
原地版改自己、返回 None: [2, 3]
difference_update: [2, 3]
issubset / 子集: False True
issuperset / 超集: False True
isdisjoint / 无交集: True True
len 与 in(哈希平均 O(1)): 2 True
frozenset 可当字典的键: 值
clear: set() 空集合 pop 会 KeyError: True
练习
- 使用random自己实现randint
- 实现一个简单的计算器,参数在启动程序时输入
- 实现函数
my_int:传入"12345",返回12345 - 实现函数
my_str:传入12345,返回"12345" - 号码归属地查询:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
335582|1860101|010|北京市|北京联通GSM卡
5583|1860100|010|北京市|北京联通GSM卡
5584|1368141|010|北京市|北京移动神州行卡
5585|1860111|010|北京市|北京联通GSM卡
5586|1358198|010|北京市|北京移动动感地带卡
5587|1361139|010|北京市|北京移动预付费卡
5588|1361138|010|北京市|北京移动神州行卡
5591|1360110|010|北京市|北京移动全球通卡
5748|1364110|010|北京市|北京移动神州行卡
10186|1581584|020|广东省广州市|广东移动全球通卡
15046|1391897|021|上海市|上海移动全球通卡
17250|1502207|022|天津市|天津移动全球通卡
21137|1345272|023|重庆市万州|重庆移动大众卡
22700|1347812|024|辽宁省沈阳市|辽宁移动大众卡
24256|1377065|025|江苏省南京市|江苏移动全球通卡
26360|1898606|027|湖北省武汉市|湖北电信CDMA卡
28709|1860802|028|四川省成都市|四川联通GSM卡
30641|1552961|029|陕西省西安市|陕西联通GSM卡
31700|1563007|0310|河北省邯郸市|河北联通GSM卡
33360|1583396|0311|河北省石家庄市|河北移动全球通卡
34825|1508122|0312|河北省保定市|河北移动全球通卡
35363|1551235|0313|河北省张家口|河北联通GSM卡
37700|1331326|0316|河北省廊坊市|河北电信CDMA卡
43500|1350358|0358|山西省吕梁市|山西移动全球通卡
43908|1553625|0359|山西省运城市|山西联通GSM卡
44521|1335360|0370|河南省商丘市|河南电信CDMA卡
50078|1509369|0378|河南省开封市|河南移动全球通卡
53603|1583981|0398|河南省三门峡|河南移动全球通卡
53916|1335897|0410|辽宁省铁岭市|辽宁电信CDMA卡
55248|1554254|0411|辽宁省大连市|辽宁联通GSM卡
58618|1374272|0427|辽宁省盘锦市|辽宁移动全球通卡
58932|1554183|0429|辽宁省葫芦岛|辽宁联通GSM卡
60268|1340475|0431|吉林省长春市|吉林移动大众卡 - 歌词解析(不强制)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21[ti:蓝莲花]
[ar:许巍]
[al:留声十年绝版青春北京演唱会]
[00:-01.70]蓝莲花
[00:-00.70]演唱:许巍
[00:00.00]
[00:00.70]没有什么能够阻挡
[00:06.01]你对自由的向往
[00:11.43]天马行空的生涯
[00:16.99]你的心了无牵挂
[00:21.20]
[02:11.55][01:50.60][00:22.63]穿过幽暗的岁月
[02:16.93][01:55.60][00:27.81]也曾感到彷徨
[02:22.21][02:01.09][00:33.13]当你低头的瞬间
[02:27.62][02:06.33][00:38.32]才发觉脚下的路
[02:31.64][02:10.23][00:42.37]
[02:32.97][00:43.79]心中那自由的世界
[02:38.23][00:49.50]如此的清澈高远
[02:43.30][00:54.31]盛开着永不凋零
[02:47.70][00:58.50]蓝莲花
[02:53.95][03:00.06][01:05.41]