Python标准库 https://docs.python.org/zh-cn/3/library/index.html
Python知识点
1、用错命令:macOs 安装完 Python 后执行报错
应该使用 python3 而不是 python
Pip知识点
查看当前安装的包
pip3 list
查看当前pip的源
pip3 config list
永久修改pip源
pip3 config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
pip3 config set global.index-url https://pypi.doubanio.com/simple
更新pip至最新版本
python3 -m pip install --upgrade pip
Python基础
PyCharm注释模板
Editor -> File and Code Templates -> Python Script
"""
${NAME} -
Author: ${USER}
Date: ${DATE}
"""
类型
# integer
a = 123
print(a, type(a))
print(type(a) == int)
# float
b = 1.23
print(b, type(b))
print(type(b) == float)
# string
c = 'hello'
print(c, type(c))
print(type(c) == str)
# boolean
d = True
print(d, type(d))
print(type(d) == bool)
# complex
e = 3 + 5j
print(e, type(e))
整数
# 十进制
a = 110
# 八进制
b = 0o110
# 十六进制
c = 0x110
# 二进制
d = 0b110
# 浮点数的科学计数法
e = 123e-5
# to binary
print(bin(47))
# to octal
print(oct(47))
# to hexadecimal
print(hex(47))
格式化输出
a1 = float(input('a1 = '))
b2 = float(input('b2 = '))
print(a1, '+', b2, '=', a1 + b2)
print('%.2f + %.2f = %.2f' % (a1, b2, a1 + b2))
print(f'{a1} + {b2} = {a1 + b2}:.2f')
运算符
# 赋值运算符 =
# 算术运算符 + - * / // % **
# 复合运算符 += -= *= /=
# 关系运算符 > < >= <= == !=
# 逻辑运算符 and or not
三元运算符
value_if_true if condition else value_if_false
如果condition
为真,则整个表达式的值为value_if_true
;如果condition
的值为假,则整个表达式的值为value_if_false
range
- range(101):可以用来产生0到100范围的整数,需要注意的是取不到101
- range(1, 101):可以用来产生1到100范围的整数,相当于前闭后开
- range(1, 101, 2):可以用来产生1到100的奇数,其中2是步长
- range(100, 0, -1):可以用来产生100到1的偶数,其中-1是步长
容器
-
列表(list)
# 创建 ## 字面量语法 nums = [10, 100, 1000] ## 构造器语法 empty = list() seq = list(range(1,100)) ## 生成式(推导式)语法 sqrt = [i ** 2 for i in range(1,10)] # 操作 nums.append(10000) nums.insert(0, 1) nums.pop() nums.remove() del nums[0] nums.index(1000) nums.clear() ## 反转 items = items[::-1] items.reverse() ## 排序(升序) items.sort() ## 排序(降序) items.sort(reverse=True) items.sort(key=int) # 将列表中数据按照整数的方式去排序 # 元素个数 len(nums) # 遍历 for i in range(len(nums)): print(nums[i]) for x in nums: print(x) for i, x in enumerate(nums): print(i, x) # 运算 ## 重复运算 repeat = [1, 10, 100] * 5 ## 成员运算 is_contains = 10 in repeat not_contains = 5 not in repeat ## 索引&切片:正向索引 0 ~ N-1 / -N ~ -1 ## 合并 list1 = [1, 3, 5, 7] list2 = [4, 4, 8] print(list1 + list2) print(list1.extend(list2)) ## 比较 list1 = list(range(1, 8, 2)) list2 = [1, 3, 5, 7, 9] ### 比较两个列表的元素是否一一对应相等 print(list1 == list2) ### 比较两个列表对应元素的大小,从头开始比 print(list1 > list2)
-
元组(tuple)
"""不可变容器""" fruits1 = ('apple', 'banana', 'grape') # 重复运算 print(fruits1 * 3) # 成员运算 print('apple' in fruits1) print('grape' not in fruits1) # 合并运算 fruits2 = ('pitaya', 'litchi') fruits3 = fruits1 + fruits2 # 索引&切片 print(fruits3[4], fruits3[-1]) print(fruits3[1:4]) print(fruits3[1:4:2]) # pack / unpack a, b = 5, 10 a, b, *c = 5, 10, 15, 20, 25 # a=5, b=10, c=[15, 20, 25] # ROT_TWO a, b = b, a # ROT_THREE a, b, c = b, c, a
-
集合(set)
"""无序性&互异性的集合""" set1 = {1, 2, 3, 4, 5} set2 = {2, 4, 6, 8} empty = set() # 注意,set = {} 定义出来的不是集合,而是字典 # 成员运算 print(1 in set1) print(1 not in set2) # 交集 print(set1 & set2) print(set1.intersection(set2)) # 并集 print(set1 | set2) print(set1.union(set2)) # 差集 print(set1 - set2) print(set1.difference(set2)) # 对称差 print(set1 ^ set2) print((set1 | set2) - (set1 & set2)) print(set1.symmetric_difference(set2))
- 字典(dict)
# 字面量语法
student1 = {"id": 1001, "name": "zhangsan", sex: 1, birthday: "1990-01-03"}
# 构造器语法
student2 = dict(id=1001, name="zhangsan", sex=1, birthday="1990-01-03")
# 生成式语法
dict1 = {i: i ** 2 for i in range(1, 10)}
# 遍历
for key in student1:
print(key)
for value in student1.values():
print(value)
for key, value in student1.items():
print(key, value)
# 运算
print('name' in student1)
dict1 = {'A': 100, 'B': 200, 'C': 300}
dict2 = {'D': 400, 'E': 500, 'A': 600}
# 更新
dict1.update(dict2)
print(dict1)
# 删除
del dict1['A']
dict1.pop('B')
dict1.popitem()
# if key is in the dictionary, return its value. if not, insert key with a value of default and return default. default defaults to None.
dict1.setdefault('C')
dict1.setdefault('K', 1000)
# 清空
dict1.clear()
变量
全局变量 - 没有写在任何函数里面的变量
局部变量 - 定义在函数内部的变量
作用域
Python搜索一个变量是按照 LEGB 顺序进行搜索的
Local(局部作用域) --> Embeded(嵌套作用域,函数中可以嵌套函数) --> Global(全局作用域) --> Build-in(内置作用域,Python标准内置数据)
在函数中想使用全局变量,需要在变量中使用 global x = 200,想在嵌套函数中使用上一级的变量,需要在变量中使用 nonlocal x = 100
__name__
__name__是一个隐藏变量,它代表当前模块(文件)的名字
"""
example1.py
"""
if __name__ == '__main__':
print("Hello world")
如果直接通过 Python 解释器运行 example.py 文件,__name__ 的值是 __main__
如果在其他的模块中导入 example.py,那么 example.py 中的 __name__ 的值就是 example
生成式语法
[expression for item in iterable if conditions]
expression:对应生成式列表的元素,是生成后需要保存的内容,expression通常利用for循环内的变量来计算表示,expression除了使用range循环外,不可忽略
for循环:语法对应基本的for循环,项item对应了可迭代对象iterable的每一个元素
if条件:用于判断循环的每个元素是否符合生成的要求标准,用于筛选循环的元素,因此不能再后面的if判断中使用else,否则失去嘞筛选的作用
# 生成一个n*n为元素的1-10的列表
list = [x*x for x in range(1,11)]
# 根据给定列表字符串集生成每个字符串的长度
list = ['ab', 'cde', 'fghj', 'jklmpb']
len_list = [len(x) for x in list]
# 生成30以内的偶数
list = [x for x in range(1, 31) if x%2==0]
# 多个整数的加法运算
def add(*args):
total = 0
for arg in args:
if type(arg) in (int, float):
total += arg
return total
def add(*args):
return sum([arg for arg in args if type(arg) in (int, float)])
print(add(1, 2, 'hello', 4))
参数
# 必备参数: 必须以正确的顺序传入函数,调用时的数量必须和声明时的一样
def multiprint(str, repeat):
print(str*repeat)
multiprint('hello', 1)
# 关键字参数:和函数调用关系紧密,函数调用使用关键字参数来确定传入的参数值
# 使用关键字参数允许函数调用时参数的顺序与声明时不一致,因为 Python 解释器能够用参数名匹配参数值
multiprint(repeat=3, str='my string')
# 默认参数:调用函数时,默认参数的值如果没有传入,则被认为是默认值
def multiprint(str, repeat=1)
print(str*repeat)
multiprint('hello world')
# 不定长参数:一个函数能处理比当初声明时更多的参数,这些参数叫做不定长参数。不定长参数有两种
# *args:一个星号,将多个参数收集到一个“元组”对象中
# **kwargs: 两个星号,将多个参数收集到一个“字典”对象中
def test(*args, **kwargs):
print(args, type(args))
print(kwargs, type(kwargs))
test(1, 2, c=3, b=2, a=1, d='hello')
>>>(1, 2) <class 'tuple'>
>>>{'c': 3, 'b': 2, 'a': 1, 'd': 'hello'} <class 'dict'>
# 命名关键字参数:关键字参数对于传入的参数名无法限制。如果想对参数名有限制,就用到了命名关键字参数
# 命名关键字参数需要一个特殊分隔符 *,*后面的参数被视为命名关键字参数
def student(name, age, *, sports):
print('name: ', name, 'age: ', age, 'sports: ', sports)
student('zhang', 23, sports='walking')
student('zhang', 23, eat='buff')
>>> Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
student('wang', 23, eat='buff')
TypeError: student() got an unexpected keyword argument 'eat'
函数
python中的函数是一等函数:
函数可以作为函数的参数;
函数可以作为函数的返回值;
函数可以赋值给变量
如果把函数作为函数的参数或者返回值,这种通常称之为高阶函数。可以实现对原有函数的解耦合操作。
# fn 是一个实现二元运算的函数
def calc(init_val, fn, *args, **kwargs):
total = init_val
for arg in args:
if type(arg) in (int, float):
total = fn(total, arg)
for value in kwargs.values():
if type(value) in (int, float):
total = fn(total, value)
return total
def add(x, y):
return x + y
def mul(x, y):
return x * y
print(calc(0, add, 11, 22, 33, 44))
print(calc(1, mul, 11, 22, 33, 44))
lambda
匿名函数:指一类无需定义标识符(函数名)的函数或子程序
def add(x, y):
return x + y
# 换成匿名函数
add = lambda x, y: x + y
print(add(2, 5))
def abs(x, y):
if x > y:
return x - y
else
return y - x
# 换成匿名函数
abs = lambda x, y: x - y if x > y else y - x
print(abs(4, 8))
map
map()
函数接收两个参数,一个是函数,一个是Iterable
,map
将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterable
返回
# 平方
def square(x):
return x * x
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(map(square, numbers)))
# 结合lambda使用
print(list(map(lambda x: x*x, numbers)))
reduce
reduce
函数接收两个参数,一个函数,一个Iterable
,reduce
将函数结果继续和序列的下一个元素做累计计算,其效果就是:
reduce(func, [1,2,3]) -> func(func(1,2), 2)
# 加法
def add(x, y):
return x + y
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(reduce(add, numbers))
# 结合lambda使用
print(reduce(lambda x: x + y, numbers))
filter
filter
函数接收两个参数,一个函数,一个Iterable
,filter
把传入的函数依次作用于每个元素,然后根据返回值是True
还是False
决定保留还是丢弃该元素
# 偶数
def even(i):
return i%2==0
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(filter(even, numbers)))
# 结合lambda使用
print(list(filter(lambda x: x%2==0, numbers)))
类
类的命名使用驼峰命名法
定义类:
- 数据抽象 - 找到和对象相关的静态特征(属性)
- 行为抽象 - 找到和对象相关的动态特征(方法)
# 学生对象
class Student:
# 通过这个来限制外部动态增加属性
__slots__ = ('name')
def __init__(self, name):
# 正常属性 public
self.name = name
# 私有属性 private 不允许外部直接修改应该加双_线
self.__name = name # private
stu = Student('lisi')
# python支持动态增加属性
stu.birthday = '1988-01'
继承
# 父类
class Person:
def __init__(self, name):
self.name = name
def eat(self):
print(f'{self.name}正在吃饭')
def play(self, game_name):
print(f'{self.name}正在玩{game_name}')
# 子类
class Student(Person):
def __init__(self, name, grade):
super().__init__(name)
self.grade = grade
def study(self, course_name):
print(f'{self.name}正在学习{course_name}')
Union
Union是 typing 模块中定义的一个类,用于表示多个类型中的任意一种类型。Union类型可以用于表示参数或函数返回值等多种情况下可能的不同类型。
语法:typing.Union[type1, type2, ...]
。使用Union类型注释能够有效地帮助代码维护者准确定义函数的输入和输出。需要注意的是,虽然 Union 类型可以用于灵活表示可选参数的类型,但是在实际使用时最好进行类型检查以确保参数类型正确。
from typing import Union
def get_int_or_str(value: Union[int, str, None]) -> Union[int, None]:
if isinstance(value, (int, str)):
return value
else:
return None
@Property
@Property 是 python 的一种装饰器,是用来修饰方法的
作用:@Property装饰器会将方法转换为相同名称的只读属性,可以与所定义的属性配合使用,这样可以防止属性被修改。
class DataSet(object):
@property
def method_with_property(self): ##含有@property
return 15
def method_without_property(self): ##不含@property
return 15
l = DataSet()
print(l.method_with_property) # 加了@property后,可以用调用属性的形式来调用方法,后面不需要加()。
print(l.method_without_property()) #没有加@property , 必须使用正常的调用方法的形式,即在后面加()
与定义的属性配合,可以防止属性被修改
class DataSet(object):
def __init__(self):
self._images = 1
self._labels = 2 #定义属性的名称
@property
def images(self): #方法加入@property后,这个方法相当于一个属性,这个属性可以让用户进行使用,而且用户有没办法随意修改。
return self._images
@property
def labels(self):
return self._labels
l = DataSet()
#用户进行属性调用的时候,直接调用images即可,而不用知道属性名_images,因此用户无法更改属性,从而保护了类的属性。
print(l.images) # 加了@property后,可以用调用属性的形式来调用方法,后面不需要加()。