方法 描述
s.add(obj) 为集合添加元素
s.update() 给集合添加元素,参数为列表,元组,字典等,也可以有多个参数
s.clear() 移除集合中的所有元素
s.copy() 拷贝一个集合
s.difference(s1) 返回集合,元素在s中不在s1中
s.discard(obj) 删除集合中指定的元素,元素不存在时不会报错
intersection() 返回集合的交集,返回新的set,如:z = x.intersection(y)
intersection_update() 返回集合的交集。在原有集合上移除,如:x = {1,2,3}, y = {1,4,5} , x.intersection_update(y)后,x={1}
s1.isdisjoint(s2) 判断两个集合是否包含相同的元素,如果没有返回 True,否则返回 False。
s1.issubset(s2) 判断指定集合是否为该方法参数集合的子集。s1是否为s2的子集
s1.issuperset(s2) 判断该方法的参数集合是否为指定集合的子集。s2是否为s1的子集
s.pop() 随机移除元素
s.remove(obj) 移除指定元素,元素不存在时报错KeyError: 'xx'
new_s=s1.symmetric_difference(s2) 返回两个集合中不重复的元素的新集合
s1.symmetric_difference_update(s2) 移除当前集合中在另外一个指定集合相同的元素,并将另外一个指定集合中不同的元素插入到当前集合中。将不重复元素存入s1
new_s = s1.union(s2) 返回两个集合的并集
len(s) 输出集合的长度
max(s) 输出集合的最大值
min(s) 输出集合最小值
方法 描述
popitem() 返回并删除字典中的最后一对键和值。
pop(key[,default]) 删除字典 key(键)所对应的值,返回被删除的值。key不存在时无default会报错KeyError: 'xx',有default则返回default
dict.values() 返回一个字典所有值的视图对象
dict.keys() 返回一个字典所有键的视图对象
dict.items() 以列表返回一个视图对象
dict.update(dict2) 把字典dict2的键/值对更新到dict里
dict.setdefault(key, default=None) 和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
key in dict 如果键在字典dict里返回true,否则返回false
dict.get(key, default=None) 返回指定键的值,如果键不在字典中返回 default 设置的默认值,没设置default则返回None
dict.fromkeys() 创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
dict.copy() 返回一个字典的浅复制
dict.clear() 删除字典内所有元素
len(dict) 计算字典元素个数,即键的总数。
方法 描述
len(list) 列表元素个数
max(list) 返回列表元素最大值
min(list) 返回列表元素最小值
list(seq) 将元组转换为列表
list.append(obj) 在列表末尾添加新的对象
list.count(obj) 统计某个元素在列表中出现的次数
list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
list.index(obj) 从列表中找出某个值第一个匹配项的索引位置,不存在时报错ValueError: 'xx' is not in list
list.insert(index, obj) 将对象插入列表
list.pop([index=-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
list.remove(obj) 移除列表中某个值的第一个匹配项,不存在时报错ValueError: list.remove(x): x not in list
list.reverse() 反向列表中元素
list.sort( key=None, reverse=False) 对原列表进行排序
list.clear() 清空列表
list.copy() 复制列表
操作 描述
len(tuple) 计算元组元素个数。
max(tuple) 返回元组中元素最大值。
min(tuple) 返回元组中元素最小值。
tuple(iterable) 将可迭代系列转换为元组。
tup[1] 读取第二个元素
tup[-2] 反向读取,读取倒数第二个元素
tup[1:] 截取元素,从第二个开始后的所有元素。
tup[1:4] 截取元素,从第二个开始到第四个元素(索引为 3)。
操作 描述
capitalize() 将字符串的第一个字符转换为大写
count(str, beg= 0,end=len(string)) 返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数
endswith(suffix, beg=0, end=len(string)) 检查字符串是否以 suffix 结束,如果 beg 或者 end 指定则检查指定的范围内是否以 suffix 结束,如果是,返回 True,否则返回 False
find(str, beg=0, end=len(string)) 检测 str 是否包含在字符串中,如果指定范围 beg 和 end ,则检查是否包含在指定范围内,如果包含返回开始的索引值,否则返回-1
index(str, beg=0, end=len(string)) 跟find()方法一样,只不过如果str不在字符串中会报一个异常。
isalnum() 如果字符串至少有一个字符并且所有字符都是字母或数字则返 回 True,否则返回 False
isalpha() 如果字符串至少有一个字符并且所有字符都是字母或中文字则返回 True, 否则返回 False
isdigit() 如果字符串只包含数字则返回 True 否则返回 False..
islower() 如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False
isspace() 如果字符串中只包含空白,则返回 True,否则返回 False.
isupper() 如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False
join(seq) 以指定字符串作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串
len(string) 返回字符串长度
lower() 转换字符串中所有大写字符为小写.
lstrip() 截掉字符串左边的空格或指定字符。
max(str) 返回字符串 str 中最大的字母。
min(str) 返回字符串 str 中最小的字母。
replace(old, new [, max]) 把 将字符串中的 old 替换成 new,如果 max 指定,则替换不超过 max 次。
rfind(str, beg=0,end=len(string)) 类似于 find()函数,不过是从右边开始查找.
rindex( str, beg=0, end=len(string)) 类似于 index(),不过是从右边开始.
rstrip() 删除字符串末尾的空格或指定字符。
split(str="", num=string.count(str)) 以 str 为分隔符截取字符串,如果 num 有指定值,则仅截取 num+1 个子字符串
startswith(substr, beg=0,end=len(string)) 检查字符串是否是以指定子字符串 substr 开头,是则返回 True,否则返回 False。如果beg 和 end 指定值,则在指定范围内检查。
strip([chars]) 在字符串上执行 lstrip()和 rstrip()
swapcase() 将字符串中大写转换为小写,小写转换为大写
title() 返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle())
istitle() 如果字符串是标题化的(见 title())则返回 True,否则返回 False
upper() 转换字符串中的小写字母为大写
isdecimal() 检查字符串是否只包含十进制字符,如果是返回 true,否则返回 false。
操作 描述
abs(x) 返回数字的绝对值,如abs(-10) 返回 10
ceil(x) 返回数字的上入整数,如math.ceil(4.1) 返回 5
floor(x) 返回数字的下舍整数,如math.floor(4.9)返回 4
cmp(x, y) 如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1。 Python 3 已废弃,使用 (x>y)-(x<y) 替换。
log(x) math.log(math.e)返回1.0,math.log(100,10)返回2.0
max(x1, x2,...) 返回给定参数的最大值,参数可以为序列。
min(x1, x2,...) 返回给定参数的最小值,参数可以为序列。
modf(x) 返回x的整数部分与小数部分,两部分的数值符号与x相同,整数部分以浮点型表示。
import math
a,b = math.modf(6.2)
print(a,b) # 0.20000000000000018 6.0
pow(x, y) x**y 运算后的值。
round(x [,n]) 返回浮点数 x 的四舍五入值,如给出 n 值,则代表舍入到小数点后的位数。
sqrt(x) 返回数字x的平方根。
from math import sqrt
print(sqrt(4)) # 2.0
choice(seq) 从序列的元素中随机挑选一个元素,比如random.choice(range(10)),从0到9中随机挑选一个整数。
randrange ([start,] stop [,step]) 从指定范围内,按指定基数递增的集合中获取一个随机数,基数默认值为 1,例如:print(random.randrange(11,29,1)),输出12
random() 随机生成下一个实数,它在(0,1)范围内。例如: r = random.random(),r值为0.46334210833597167
shuffle(lst) 将序列的所有元素随机排序,例如:random.shuffle(list),执行后会随机打乱list的值
uniform(x, y) 随机生成下一个实数,它在[x,y]范围内。例如:print(random.uniform(2,8)),输出6.109074709791044

#
print(hex(21)) # 0x15
#
print(oct(21)) # 0o25
#
print(bin(21)) # 0b10101
# 0b
print(bin(21)[2:]) # 10101
#
print(bin(21)[2:].zfill(2*4)) # 00010101
#
print(int('0x15',16)) # 21
#
print(int('0o25',8)) # 21
#
print(int('0b10101',2)) # 21
multi_array = [[1,2,3],[4,5],[6],[7,8,9]]
linear_array = [i for item in multi_array for i in item]
print(linear_array) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(divmod(10,3)) # (3, 1)
quotient,remainder = divmod(10,3)
print(quotient,remainder) # 3 1
x=64
n=6
print(x**(1/n)) # 2.0
x=2
n=6
print(x**n) # 64
#
def func(n):
if n == 0:
return 0
else:
return n + func(n - 1)
print(func(4)) # 10
#
def func_b(n):
return n * (n + 1) / 2
print(func_b(4)) # 10.0
#
def func(n):
if n == 1:
return 1
else:
return n * func(n - 1)
print(func(4)) # 24
def fab_a(n):
""""""
a, b, count = 0, 1, 0
while count < n:
yield a
a, b = b, a + b
count += 1
def fab_b(n):
""""""
if n <= 1:
return n
else:
return fab_b(n - 1) + fab_b(n - 2)
f = fab_a(10)
while True:
try:
print(next(f), end=' ') # 0 1 1 2 3 5 8 13 21 34
except StopIteration:
break
print()
for i in range(10):
print(fab_b(i), end=' ') # 0 1 1 2 3 5 8 13 21 34
def insert_sort(lst: list) -> list:
"""
1. 2
2. 1
3. 1
4.
"""
for i in range(1, len(lst)):
j = i - 1
tmp = lst[i]
while tmp < lst[j] and j >= 0:
lst[j + 1] = lst[j]
j -= 1
lst[j + 1] = tmp
init_list = [8, 6, 9, 10, 2, 16, 0, 3, 7, 4, 2]
insert_sort(init_list)
print(init_list) # [0, 2, 2, 3, 4, 6, 7, 8, 9, 10, 16]
def selection_sort(lst:list)->None:
"""
1. 1
2.
3. 1
"""
for i in range(len(lst)):
min_index = i
for j in range(i+1,len(lst)):
if lst[min_index] > lst[j]:
min_index = j
lst[i],lst[min_index] = lst[min_index],lst[i]
dec = '10'
b = b'11'
chi = ''
arab = 'IV'
print(dec.isdigit()) # true
print(dec.isnumeric()) # true
print(dec.isdecimal()) # true
print(b.isdigit()) # true
print(b.isnumeric()) # AttributeError: 'bytes' object has no attribute 'isdecimal'
print(b.isdecimal()) # AttributeError: 'bytes' object has no attribute 'isdecimal'
print(chi.isdigit()) # False
print(chi.isnumeric()) # True
print(chi.isdecimal()) # False
print(arab.isdigit()) # False
print(arab.isnumeric()) # False
print(arab.isdecimal()) # False
import string
a = ''
count = 0
for item in string.ascii_lowercase: #
if item in a:
count += 1
break
for item in string.ascii_uppercase: #
if item in a:
count+=1
break
for item in string.digits: #
if item in a:
count+=1
break
for item in string.punctuation: #
if item in a:
count+=1
break
import pytest
#
@pytest.fixture(autouse=True)
def fix():
print('This is a fixture function!')
yield
print('end')
class TestClass:
def test_class_one(self):
assert 1 == 1
def test_class_two(self):
assert 1 in [1, 2, 3]
def test_one():
assert 1 == 1
#
@pytest.mark.skip(reason='')
def test_two():
assert 'a' in 'bac'
#
@pytest.mark.skipif(pytest.__version__ < '8', reason='7')
def test_three():
assert 4 > 5
@pytest.mark.run(order=2) # 2
@pytest.mark.xfail(pytest.__version__ < '8', reason='')
def test_four():
assert 2 == 2
# pytest-ordering
@pytest.mark.parametrize(('var', 'pwd'), [(1, 9), (2, 4), (3, 9)])
@pytest.mark.run(order=1) # 1
def test_five(var, pwd):
assert var + pwd < 11
# pytest-rerunfailures
# pytest -v --reruns 2 --reruns-delay 5 test_rerun.py
#
@pytest.mark.flaky(reruns=2, reruns_delay=3) # 3
def test_six():
assert 'a' in ['b', 'c']

写在表达式后面,可以更好地控制格式化值的方式

# pi
import math
print(f'The value of pi is approximately {math.pi:.3f}.') # The value of pi is approximately 3.142.
# ':'
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
for name, phone in table.items():
print(f'{name:10} ==> {phone:10d}')
# Sjoerd ==> 4127
# Jack ==> 4098
# Dcab ==> 7678
# '!a' ascii() '!s' str()'!r' repr()
animals = 'eels'
print(f'My hovercraft is full of {animals}.') # My hovercraft is full of eels.
print(f'My hovercraft is full of {animals!r}.') # My hovercraft is full of 'eels'.
# = 3.12
bugs = 'roaches'
count = 13
area = 'living room'
print(f'Debugging {bugs=} {count=} {area=}') # Debugging bugs='roaches' count=13 area='living room'
# global nonlocal
# global nonlocal
def scope_test():
def do_local():
spam = "local spam"
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print("After local assignment:", spam) # After local assignment: test spam
do_nonlocal()
print("After nonlocal assignment:", spam) # After nonlocal assignment: nonlocal spam
do_global()
print("After global assignment:", spam) # After global assignment: nonlocal spam
scope_test()
print("In global scope:", spam) # In global scope: global spam

实例变量用于每个实例的唯一数据,而类变量用于类的所有实例共享的属性和方法

class Dog:
kind = 'canine' # class variable shared by all instances
def __init__(self, name):
self.name = name # instance variable unique to each instance
d = Dog('Fido')
e = Dog('Buddy')
print(d.kind) # 'canine' # shared by all dogs
print(e.kind) # 'canine' # shared by all dogs
print(d.name) # 'Fido' # unique to d
print(e.name) # 'Buddy' # unique to e
# tricks Dog :
class Dog:
tricks = [] # mistaken use of a class variable
def __init__(self, name):
self.name = name
def add_trick(self, trick):
self.tricks.append(trick)
d = Dog('Fido')
e = Dog('Buddy')
d.add_trick('roll over')
e.add_trick('play dead')
print(d.tricks) #['roll over', 'play dead'] # unexpectedly shared by all dogs
# 使:
class Dog:
def __init__(self, name):
self.name = name
self.tricks = [] # creates a new empty list for each dog
def add_trick(self, trick):
self.tricks.append(trick)
d = Dog('Fido')
e = Dog('Buddy')
d.add_trick('roll over')
e.add_trick('play dead')
print(d.tricks) # ['roll over']
print(e.tricks) # ['play dead']
# :
class Warehouse:
purpose = 'storage'
region = 'west'
w1 = Warehouse()
print(w1.purpose, w1.region) # storage west
w2 = Warehouse()
w2.region = 'east'
print(w2.purpose, w2.region) # storage east

由于存在对于类私有成员的有效使用场景(例如避免名称与子类所定义的名称相冲突),因此存在对此种机制的有限支持,称为名称改写。 任何形式为 __spam 的标识符(至少带有两个前缀下划线,至多一个后缀下划线)的文本将被替换为 _classname__spam

class Donkey:
__age = 18
_name = 'grig'
gender_ = ''
__hometown_ = ''
__height__ = '160cm'
def update(self):
print(f'Donkey\'update')
__update = update
class SubDonkey(Donkey):
def update(self):
print(f'SubDonkey\'update')
__update = update
sb = SubDonkey()
sb.__update() # AttributeError: 'SubDonkey' object has no attribute '__update'AttributeError: 'SubDonkey' object has no attribute '__update'
sb._Donkey__update() # Donkey'update
sb.__update() # AttributeError: 'SubDonkey' object has no attribute '__update'
sb._SubDonkey__update() # SubDonkey'update
print(sb._Donkey__age) # 18
print(sb._name) # grig
print(sb.gender_) #
print(sb._Donkey__hometown_) #
print(sb.__height__) # 160cm
class Employee:
name: str
dept: str
salary: int
emp = Employee('grig', 'clab', 1800) # TypeError: Employee() takes no arguments
# 使 dataclasses
from dataclasses import dataclass
@dataclass
class Employee:
name: str
dept: str
salary: int
emp = Employee('grig', 'clab', 1800) # TypeError: Employee() takes no arguments
emp.name = 'Bob'
print(emp.name) # Bob
print(emp.salary) # 1800

glob 模块提供了一个在目录中使用通配符搜索创建文件列表的函数

import glob
print(glob.glob('*.py')) # ['primes.py', 'random.py', 'quote.py']
import shutil
shutil.copyfile('data.db', 'archive.db')
shutil.move('/build/executables', 'installdir')

命令行参数以列表形式存储在 sys 模块的 argv 属性中

import sys
print(sys.argv)

在命令行中运行 python demo.py one two three 输出的结果

['demo.py', 'one', 'two', 'three']

argparse 模块提供了一种更复杂的机制来处理命令行参数

import argparse
parser = argparse.ArgumentParser(
prog='top',
description='Show top lines from each file')
parser.add_argument('filenames', nargs='+')
parser.add_argument('-l', '--lines', type=int, default=10)
args = parser.parse_args()
print(args)
import statistics
data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
print(statistics.mean(data)) # 1.6071428571428572
print(statistics.median(data)) # 1.25
print(statistics.variance(data)) # 1.3720238095238095
def average(values):
"""Computes the arithmetic mean of a list of numbers.
>>> print(average([20, 30, 70]))
40.0
>>> print(average((1,2,3)))
2.0
"""
return sum(values) / len(values)
import doctest
doctest.testmod()

参考链接

from jsonpath import jsonpath
d = {
'status_code':200,
'desc':'',
'data':[
'123',
'345',
789
]
}
print(jsonpath(d,'$.desc')) # ['']
print(jsonpath(d,'$.data[3]')) # False
whitespace = ' \t\n\r\v\f'
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_letters = ascii_lowercase + ascii_uppercase
digits = '0123456789'
hexdigits = digits + 'abcdef' + 'ABCDEF'
octdigits = '01234567'
punctuation = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
printable = digits + ascii_letters + punctuation + whitespace
c = 'a'
a = 101
print( c + " ASCII ", ord(c)) # a ASCII 97
print( a , " ", chr(a)) # 101 e
lst = [1, 2]
m1, n1 = lst
print(m1) # 1
print(n1) # 2
dic = {
"ka": 123,
"kb": 234
}
m2, n2 = dic
print(m2) # ka
print(n2) # kb
st = {1, 2}
m3, n3 = st
print(m3) # 1
print(n3) # 2
tup = (1, 2)
m4, n4 = tup
print(m4) # 1
print(n4) # 2
tup = [1, 2, 3]
m5, n5 = tup
print(m5) # ValueError: too many values to unpack (expected 2)
a = 12.12300 # 12.123
b = 12.00 # 12
c = 200.12000 # 200.12
d = 200.10 # 200
e = 11.0 # 11
# str
print(str(a)) # 12.123
print(str(b)) # 12.0
print(str(c)) # 200.12
print(str(d)) # 200.1
print(str(e)) # 11.0
# 使+
print([str(a),int(a)][int(a)==a]) # 12.123
print([str(b),int(b)][int(b)==b]) # 12
print([str(c),int(c)][int(c)==c]) # 200.12
print([str(d),int(d)][int(d)==d]) # 200.1
print([str(e),int(e)][int(e)==e]) # 11
lst = ['1', '2.3', '6']
#
print(lst) # ['1','2.3','6']
#
print('[' + ', '.join(lst) + ']') # [1, 2.3, 6]