栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python刷题好用的一些方法总结

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python刷题好用的一些方法总结

目录
  • 优先队列
  • collections
    • Counter
    • defaultdict
    • OrderedDict
    • deque
    • namedtuple
  • 整数变二进制,二进制变整数
  • 字母变数字,数字变字母
  • 设置递归深度
  • 读到文件结束
  • python 重定向

优先队列

import heapq
a = []
nums = 0 # 数字,默认是小根堆 从小到大排序
heapq.heappush(a,nums)
heapq.heappop(a) # 弹出堆顶

#heapq.heapfy(list) 将一个列表转换为小根堆
#heappushpop(heap,item) 同时pop以及添加item,先push,再pop
#heapreplace(heap.item) 先pop,再push

heapq.heapify(x): O(n)
heapq.heappush(heap, item): O(logn)
heapq.heappop(heap): O(logn)
collections

元组比列表更简洁

Counter

字典的字类,提供了可哈希对象的计数功能
from collections import Counter
统计元素出现次数

defaultdict

字典的字类,提供了一个工厂函数,为字典查询提供了默认值
from collections import defaultdict

OrderedDict

字典的字类,保留了他们被添加的顺序
from collections import OrderedDict()
c = OrderedDict()

deque

from collections import deque

函数名解释
append(x)添加x到右端
appendleft(x)添加x到左端
clear()清楚所有元素,长度变为0
copy()创建一份浅拷贝
count(x)计算队列中个数等于x的元素
extend(iterable)在队列右侧添加iterable中的元素
extendleft(iterable)在队列左侧添加iterable中的元素,注:在左侧添加时,iterable参数的顺序将会反过来添加
index(x[,start[,stop]])返回第 x 个元素(从 start 开始计算,在 stop 之前)。返回第一个匹配,如果没找到的话,升起 ValueError 。
insert(i,x)在位置 i 插入 x 。注:如果插入会导致一个限长deque超出长度 maxlen 的话,就升起一个 IndexError 。
pop()移除最右侧的元素
popleft()移除最左侧的元素
remove(value)移去找到的第一个 value。没有抛出ValueError
reverse()将deque逆序排列。返回 None 。
maxlen队列的最大长度,没有限定则为None。
namedtuple

创建命名元组子类的工厂函数

from collections import namedtuple
Person = namedtuple('Person', ['age', 'height', 'name'])
Human = namedtuple('Human', 'age, height, name')
Human2 = namedtuple('Human2', 'age height name')
tom = Person(30,178,'Tom')
jack = Human(20,179,'Jack')
tom
Person(age=30, height=178, name='Tom')
 jack
Human(age=20, height=179, name='Jack')
tom.age #直接通过  实例名+.+属性 来调用
30
jack.name
'Jack'
整数变二进制,二进制变整数

python bin()函数
bin 函数可以把一个数转化为二进制数
int(str(num),2) 将二进制数转化为整数

字母变数字,数字变字母

py将字母变成数字的内置函数
ord(‘F’) = 70
chr(70) = ‘F’

设置递归深度

python 设置递归深度
import sys
sys.setrecursionlimit(1000)

读到文件结束
try:
	while True:
		s = input()
except EOFError: 
	pass
python 重定向
import sys
files = open('test.txt', 'r') 从文件中读(使用input()读入)
sys.stdin = files
file = open('test2.txt', 'w')
sys.stdout = file  # 标准输出重定向至文件

try:
	while True:
		s = input() # 从test.txt中读取数据
		print(s) # 存入test2.txt文件中
except EOFError: 
	pass
files.close()
file.close()
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/942149.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号