py啥都能干, web,数据处理,爬虫,目下最火的AI应用开发. 以下整理完全随机,不讲究思路
可变类型 : list [], dict {} 传地址
不可变类型: string , num , tuple 传值 , str 的strip返回副本非原地
is : 比较两个对象的id 是否相同
== : 比较两个对象的值是否先等 , 默认使用对象的 eq 方法比较
奇数列表表达式 [i for i in a if i%2==1]
偶数位置是偶数的列表 [i for i in range(len(nums)) if i %2==0 and nums[i]%2==0 ]
python 中reverse 链表
1. list.reverse() mylist = [1,2,3,4,5] mylist.reverse() = [5,4,3,2,1] #直接在原列表上进行反转。
2. 切片[::-1] mylist=[1,2,3,4,5] reversed=mylist[::-1] [5,4,3,2,1] # 直接在原列表上进行反转。
3. 使用reversed() 函数 , mylist=[1,2,3,4,5] reversed = list(reversed(mylist)) [5,4,3,2,1] # 返回一个反转的迭代器,可以通过 list() 转换为列表。
python 中dict字典操作:
in 判断key 在字典中存在 if key in dict: 直接 dict[key] 不存在时会异常
in 判断字典中存在 if value in dict.values()
但没有直接获取 value 对应key 的方法, 即可以通过key 获取value 无法反查. 此时必须使用辅助函数.
```
my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 2, 'e': 4}
# 要查找的值
target_value = 2
# 存储所有匹配的键
matching_keys = [key for key, value in my_dict.items() if value == target_value]
# 判断值是否存在
if matching_keys:
print(f"The value {target_value} exists in the dictionary.")
print(f"The keys corresponding to the value {target_value} are: {matching_keys}")
else:
print(f"The value {target_value} does not exist in the dictionary.")
```
python 的set()
增删改查 单增add(),多增update(),删 remove(),discard(),pop(),clear() 修改先删后加, 查in not in
对二叉搜索树的中序遍历 是个递增的数列
python 中没有三元运算符. 使用 max_value = x if x > y else y 条件表达式
python 中没有PHP_INT_MAX 使用 float('inf') float('-inf') 表示极大整数, 和 极小负数 使用sys.maxsize 表示当前系统上的最大整数值
collections 是python 标准库中的一个模块,提供了多种有用的数据结构.
Counter , 计数
```
from collections import Counter
ab = Counter([a + b for a in nums1 for b in nums2])
print(most_common(ab))
```
dd 默认值字典
from collections import defaultdict
dd = defaultdict(int) # 默认返回0
dd['a'] += 1
from collections import deque
deque 双向队列
d = deque(['a', 'b', 'c'])
# 常用方法
d.append('d') # 右侧添加
d.appendleft('z') # 左侧添加
d.pop() # 右侧弹出
d.popleft() # 左侧弹出
d.rotate(1) # 向右旋转
d.rotate(-1) # 向左旋转
d.extend(['e', 'f']) # 右侧扩展
d.extendleft(['x', 'y']) # 左侧扩展
zfill 左补零
number = 42
padded_number = str(number).zfill(5)
print(padded_number) # 输出: 00042
字符串截取:后面的内容
s = "E000:974407"
colon_index = s.rfind(':') # 找到最后一个冒号的位置
number = s[colon_index + 1:]
print(number) # 输出: 974407
s = "E000:974407"
parts = s.split(':')
number = parts[-1] # 获取最后一个部分
print(number) # 输出: 974407
截取: 前面的内容
s = "E000:974407"
ret = s[:s.find(":")]
list 合并为逗号分隔字符串 s = ",".join(list) , join 要求 list 内的元素都是str, 转义下 l = [str(s) for s in list] 或者 l = map(str,list); map 返回的是迭代器,惰性生成,使用时再生成, 列表表达式立即生成, map 省内存; join 的参数是迭代器, . 是成员访问运算符
拆分为 列表 l = s.split(",") string.split 单字符分割, re.split(r'[,; ]', text) 多字符分割
s.lstrip('x') 去掉开头 s.rstrip() 去掉结尾 s.strip() 去掉两端
字典的所有key列表: dict.keys() ; 字典的所有值列表: dict.values(); for 遍历dict 默认为key; 使用 for k,v in dict.items() 得到k,v;
字典复制 用 import copy , copy.deepcopy() 深复制;浅复制用copy.copy() 或dict.copy()
__iter__() 和__next()__ 是迭代器的两个核心方法, iter() 定义一个对象如何成为可迭代对象,next返回
用//向下取整 match.ceil() 向上取整,round()四舍五入,math.floor()向下
py 是动态强类型语言, php 是动态弱类型语言, 动态指的是变量类型在运行时确定,强类型是不可以隐式类型转换。 静态类型在编译前必须确定变量类型 java、go、c++、c# 是静态语言
monkey patch 猴子补丁,运行时属性替换。
自省:运行时判断一个对象的类型的能力。
is 判断的时候是内存地址, == 判断是两个值是否相同, 比如 xx is None None 是单例的内存地址唯一
字典推导式: 合并两个list 为字典
a =['a', 'b','c'] b =[1,2,3]
dictA={k:v for k,v in zip(a,b)}
zip可以当多个列表打包成元组。
python 2 3 差异:python print 成为函数,除法返回浮点数 // ,string默认unicode
python 2 :print 是关键字, 字符串s=u'中文' type(s) 为unicode ,
python 3 : 类型提示 type hint 注解, super , 解包 a,b *c = rang(10) // a =1 b =2 c = [剩下的]
asyncio 异步 async/await 原生协程
函数如何传参:可变类型, 不可变类型
https://docs.python.org/zh-cn/3/library/math.html
list.sort()原地 sorted() 非原地内置, sort(arr, key=lambda x:(-x[0], x[1])) 按照 x 第0个元素的降序,第一个元素升序的方式排序;
进制转换 : int('0x11',16) int('0o77',8) int('0b11',2) 转为10进制; bin(12);oct(89);hex(99)
Exception 常规错误的基类, BaseException 所有异常的基类,Base中包括KeyboardException ctrl^c 一般用Exception
python 由于存储精度问题, round()函数四舍五入会有问题, 需要用decimal 类精确计算 ,
import decimal decimal.Decimal('3.67').quantize(Decimal('0.00'))
设置decimal 为四舍五入模式 :
from decimal import getcontext, ROUND_HALF_UP
getcontext().rounding = ROUND_HALF_UP # 设置为“四舍五入”
模式名称 | 描述 | 符号 |
---|---|---|
ROUND_CEILING | 总是向正无穷方向舍入(如上界)。例如 1.1 → 2.0 。 | ⬆ |
ROUND_FLOOR | 总是向负无穷方向舍入(如下界)。例如 1.9 → 1.0 。 | ⬇ |
ROUND_DOWN | 截断尾数,不进行任何进位(类似数学中的“地板除”)。 | → |
ROUND_UP | 总是向远离 0 的方向进位(如 1.1 → 2.0 ,-1.1 → -2.0 )。 | ↑ |
ROUND_HALF_UP | 传统四舍五入(最常见)。例如 1.5 → 2 ,1.499 → 1 。 | ⬆⬇ |
ROUND_HALF_DOWN | 类似四舍五入,但“半中间”舍去而不是进位。例如 1.5 → 1 ,1.501 → 2 。 | ⬆⬇ |
ROUND_HALF_EVEN | 银行家舍入法(避免累加偏移)。例如 1.5 → 2 ,2.5 → 2 。 | ⬆⬇ |
ROUND_05UP | 当最后一位是 0 或 5 时进位,否则舍去。常用于某些特定场景(如会计)。 | 特殊规则 |
list 插入元素: 1 list.insert(1,x) 2 new_list = list + ['x']
py 中用matrix=[][] 声明二维数组报错, 第二个[]py会进行动态索引报错IndexError
matrix=[[0]*col] * row 这种生成每个row相同,改一个影响所有
正确的为每个row初始化 matrix = [[0 for _ in range(col)] for _ in range(row) ]
将string 转换为list list(string) 最快 [x for x in s]
python 的int 是任意精度的, 超大整数加减乘除不需要考虑溢出问题,只要内存够用就可以。
变量作用域 LEGB := local -> enclosing -> global -> builtins 由远到近
from package import module
from module import MyClass
从规范的名称上看出来 是从包导入的模块, 还是从模块中导入的类。
nonlocal xx 只用于函数嵌套 将xx 的作用域提升一层 使用上一层的 xx 变量, 不会新声明变量。
global 可以声明全局变量, 全局有的话就直接用。