Python
Vincent__Lai
这个作者很懒,什么都没留下…
展开
-
【Python】可设置抽奖者权重的抽奖脚本
抽奖系统包含如下特点:1、可给不同抽奖者设置不同的权重2、先从价值高的奖品开始抽3、已经中奖的人,不再参与后续的抽奖原创 2022-11-27 16:03:51 · 1180 阅读 · 1 评论 -
【算法】找到单次出现的元素最佳方法——异或
背景Leetcode 389. 找不同 (https://leetcode-cn.com/problems/find-the-difference/),以为用ASCII码值相减已经很快了,没想到还有更骚的——直接异或。。。附上大神代码,被秀的头皮发麻class Solution: def findTheDifference(self, s: str, t: str) -> str: res = 0 for i in s + t :原创 2022-03-20 12:32:54 · 699 阅读 · 1 评论 -
【Python】用哈希表来提高查询“元素“to“元素“效率
背景Leetcode 506. 相对名次(https://leetcode-cn.com/problems/relative-ranks/),这道题思路很简单,就是排序,然后找到返回排序后的索引。代码优化一开始写的代码是:score = [10, 3, 8, 9, 4]score_sort = sorted(score, reverse=True)res = []for s in score: loc = score_sort.index(s) if loc == 0:原创 2022-03-20 11:44:39 · 1464 阅读 · 0 评论 -
【Python】collections.Counter快速统计元素个数,免去手动构造字典的烦恼
用法用collections.Counter来快速统计元素个数:import collectionsa = collections.Counter("sdfdsgsdfdfssfd") #把所有元素出现的次数统计下来了print(a)输出结果:Counter({‘s’: 5, ‘d’: 5, ‘f’: 4, ‘g’: 1})具体案例Leetcode 409. 最长回文串 可用collections.Counter来快速解题。(https://leetcode-cn.com/probl原创 2022-03-20 10:53:12 · 817 阅读 · 1 评论 -
【算法】用计算机思维求解“12个硬币其中一个为假,三次称量找到假硬币”问题(附代码)
背景题目是这样子的:有12枚硬币,其中有一枚假币,而且真币与假币谁轻谁重不知,如何通过三次称量判断出哪枚是假币?这是一道很经典的逻辑推理题,乍一看感觉很想脑筋急转弯,但是其实完全可以用计算机思维去系统的解这道题。如果能够掌握系统的思维,这样就可以举一反三,解决更多的问题。——毕竟总不能啥都用人都推理吧?万一数据量变大了怎么办呢?例如39个硬币称4次要怎么称?这道题的关键:状态。——天平的状态、硬币的状态。思路首先,天平的状态只有3种可能:左边重、右边重、平衡。如果用计算机语言表示:左边重原创 2022-03-19 10:35:01 · 4152 阅读 · 0 评论 -
【Python】selenium本地网页内容代码保存demo
功能介绍打开本地html,定位到特定内容,然后保存该内容对应的html到txt中代码from selenium import webdriverfrom tqdm import tqdmdef write_txt(txt_list, txt_name): with open(txt_name, 'a+', encoding='utf-8') as f: for txt in txt_list: f.write(txt+'\n\n')def lo原创 2021-09-26 00:45:48 · 781 阅读 · 1 评论 -
【Python】并行运行多个cmd命令
使用场景有时候需要同时运行多个cmd命令,如果手动打开一个个cmd再输入指令的话,就会非常慢。如果通过&符号使得命令连续运行,指令是有先后顺序的(即串行的),运行完一条才会运行下一条,效率也很低,所以我们可以通过多线程来并行多个cmd命令。代码下面的代码功能相当于开了两个窗口,分别运行python main.py --model yolo和python main.py --model centernet:#!/usr/bin/python# encoding=utf-8import原创 2021-02-20 17:05:09 · 10172 阅读 · 4 评论 -
【Python】ValueError: unsupported pickle protocol: 5解决方案
问题描述使用pickle.load(f)读取pkl文件的时候,报错ValueError: unsupported pickle protocol: 5解决方案原因是由于保存pkl文件的版本是python3.8,而读取的时候用了python3.7来读取,所以才会报错。解决办法就是:保存和读取pkl文件用同样的python版本...原创 2021-02-05 11:30:47 · 21983 阅读 · 1 评论 -
【Python】判断一个数组中是否包含另一个数组
y1 = np.array([[1, 2], [1, 3], [1, 2], [2, 2]])y2 = np.array([[100, 200], [100,300], [100, 200], [200, 200]])z = np.array([1, 2])(y1 == z).all(1).any()# True(y2 == z).all(1).any()# False参考:关于python:检查NumPy数组是否包含另一个数组...转载 2021-01-25 10:17:59 · 7665 阅读 · 2 评论 -
【Python】logging模块demo
有时候我们希望代码可以实时输出进度,同时这些进度又可以实时保存进txt里面,这个时候就可以用到logging模块下面这一段是demo代码import loggingdef Logger(logger_name): logger = logging.getLogger(__name__) logger.setLevel(level=logging.INFO) handler = logging.FileHandler(logger_name) handler.setLe原创 2021-01-17 17:00:56 · 256 阅读 · 0 评论 -
【Python】argparse模块demo
有时候可能同一段代码需要运行多次,每次只是几个参数不同,这个时候可以用到argparse模块,只需要改变命令行的参数就可以,代码变量不需要改来改去。下面是一段demo,参数改成你自己的就好了:import argparseimport osimport datetimedef get_args(): parser = argparse.ArgumentParser(description='Test') parser.add_argument('--epoch', defaul原创 2021-01-17 16:20:08 · 196 阅读 · 2 评论 -
【Python】numpy数组按照指定列由大到小排序方法
import numpy as npa = np.array([[8.0000000e+01, 1.9200000e+02, 1.2800000e+02, 3.1100000e+02, 9.7027886e-01], [5.6000000e+01, 1.9300000e+02, 8.1000000e+01, 2.5200000e+02, 1.0378717e-01], [2.7900000e+02, 1.3900000e+02, 3.0700000e+02, 2.1100000e+02, 7.30104原创 2021-01-15 10:02:49 · 7230 阅读 · 0 评论 -
【Pycharm】CreateProcess error = 2,系统找不到指定的文件
问题描述用SSH连接服务器debug的时候,显示报错CreateProcess error = 2,系统找不到指定的文件,但是明明这个文件在本地和服务器都是有的解决方案选择“Run”-“Edit Configurations”,删除那个提示报错的代码例如我报错的代码是genetic_algorithm.py,就删掉它,然后再重新选择“Run”-“Run”j就好了...原创 2021-01-15 09:40:00 · 1777 阅读 · 2 评论 -
【Python】numpy将数组按顺序排列后又重新还原原来顺序的方法
前言有时候会遇到一些场景,需要我们对数据排序后,进行某一些处理,然后又让我们的数据恢复成原来的排序,在网上搜了下发现没有现成的demo,所以这里记录一下一维情况import numpy as nparr = np.array([2, 1, 3, 5, 2, 44, 11])print('原来顺序:', arr)order = np.argsort(-arr)arr = sorted(arr, reverse=True)print('排序后顺序:',arr)recovery_arr =原创 2021-01-11 16:44:54 · 4125 阅读 · 2 评论 -
【Python】matplotlib绘制热力图代码
文档地址:matplotlib.axes.Axes.imshowCreating annotated heatmaps实在是太全了,而且例子也很简单易懂,没什么可说的了,mark一下。。。原创 2021-01-08 15:12:31 · 1219 阅读 · 0 评论 -
【Python】opencv中的颜色问题
在cv2中,color的通道顺序不是RGB,而是BGR,所以在画图过程中(例如下面的代码):(255, 0, 0)实际上是蓝色而不是红色,红色应为(0, 0, 255)# bb的格式为:[xmin, ymin, xmax, ymax]cv2.rectangle(img, (int(bb[0]), int(bb[1])), (int(bb[2]), int(bb[3])), color, 2)附上三原色原原创 2021-01-05 11:24:59 · 817 阅读 · 0 评论 -
【Python】多种类直方图绘制demo
import seaborn as snsimport numpy as npimport matplotlib.pyplot as pltnp.random.seed(0)x1=np.random.randn(50)np.random.seed(1)x2=np.random.randn(50)plt.figure(dpi=120)sns.set(style='dark')sns.set_style("dark", {"axes.facecolor": "#e9f3ea"})g=sns原创 2020-12-30 14:47:02 · 1218 阅读 · 0 评论 -
【Pytorch】快速输出网络模型信息方法
首先,安装torchsummarypip isntall torchsummary下面是demo代码,其中(3, 100, 100)分别为单张图片的通道数、高、宽from torchsummary import summaryimport torchvisionimport torchdef model_info(model): device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') back原创 2020-12-28 10:51:36 · 1717 阅读 · 1 评论 -
【Python】opencv2画行人检测框常用代码
import cv2import numpy as npdef cv_imread(filePath): cv_img = cv2.imdecode(np.fromfile(filePath,dtype=np.uint8), -1) return cv_img# 需要可视化的图片地址img_path = ‘’# 对应图片的检测结果detection_result = []# 如果路径中包含中文,则需要用函数cv_imread的方式来读取,否则会报错img = cv_im原创 2020-11-17 11:05:39 · 707 阅读 · 0 评论 -
【Python】装饰器通俗解释
【Python三分钟】什么是装饰器?原创 2020-10-17 00:44:39 · 110 阅读 · 0 评论 -
【Python】实现排列组合
import itertoolsres = []for i in itertools.permutations('123', 3): res.append(''.join(i))# 输出 ['123', '132', '213', '231', '312', '321']print(res)参考:python解决排列组合原创 2020-08-31 09:59:25 · 750 阅读 · 0 评论 -
【Python】json文件读写
读jsonimport jsonjson_file = ''with open(json_file, 'r', encoding='utf8') as fp: json_data = json.load(fp)写jsonimport jsonjson_file = '1.json'dict1 = [{'name': 'Tom', 'age': 10}, {'name': 'Marry', 'age': 18}]with open(json_file,'w',encoding='ut原创 2020-07-28 19:57:00 · 554 阅读 · 0 评论 -
【Python】带负数的切片操作速记
只要记住后面的式子就好了:[start_index: stop_index: step]start_index是切片的起始位置stop_index是切片的结束位置(不包括)step可以不提供,默认值是1,步长值不能为0,不然会报错ValueError例如,a = [1,2,3,4,5]a[-2:]表示start_index=-2,一直取值到结束,step=1,所以结果为[4,5]a[:-2]表示stop_index=-2,start_index为默认的0,step=1,所以结果为[1,2,3]原创 2020-07-05 20:01:27 · 2794 阅读 · 0 评论 -
【Python】合并多张图片为一行/一列
import cv2import numpy as npdef concatenate_img(img_list, img_name, axis=1): img_list = [cv2.imread(img) for img in img_list] img = np.concatenate(([i for i in img_list]), axis=axis) cv2.imwrite(img_name, img)img_list = [''] # 图片的本地地址# 合并原创 2020-06-07 21:19:28 · 1474 阅读 · 1 评论 -
【Python】直方图绘制代码
#绘制直方图def drawHist(heights):#创建直方图#第一个参数为待绘制的定量数据,不同于定性数据,这里并没有事先进行频数统计#第二个参数为划分的区间个数bins = np.arange(0, 1.01, 0.01)n, bins, patches = pyplot.hist(heights, bins)pyplot.xlabel(‘归一化后数值’)pyplot.ylabel(‘频次’)pyplot.title(‘第5天归一化后数值区间统计’)pyplot.show()原创 2020-06-05 15:31:23 · 1556 阅读 · 0 评论 -
【Python】正则表达式快速调用
提取DetectedText后的结果import redata = '{"TextDetections": [{"DetectedText": "梁非凡也有了质疑", "Confidence": 99, "Polygon": [{"X": 264, "Y": 42}, {"X": 420, "Y": 42}, {"X": 420, "Y": 63}, {"X": 264, "Y": 63}], "AdvancedInfo": "{\"Parag\":{\"ParagNo\":1}}", "ItemPol原创 2020-06-04 12:12:12 · 176 阅读 · 0 评论 -
【Python】通过pyhanlp提取关键词
from pyhanlp import *# 关键词提取def extractKeyword(document, keyword_num=2): return HanLP.extractKeyword(document, keyword_num)if __name__ == '__main__': document = '' # 返回list形式 keywords = list(extractKeyword(document keyword_num=2)) # 若需要进一步处理变成原创 2020-06-03 12:16:13 · 1833 阅读 · 1 评论 -
【Python】获得某一目录下的所有图片(按照图片名字排序)
import osimg_folder = ''img_list = [os.path.join(img_folder, nm) for nm in os.listdir(img_folder) if nm[-3:] in ['jpg','png','gif']]img_list.sort()建议大家图片命名的时候不要简单的用单个数字,这样在图片sort排序的时候,会出现11.jpg排在2.jpg前面建议加上zfill()避免上述的排序问题idx = 1img_name = str(idx)原创 2020-06-03 12:03:20 · 1422 阅读 · 0 评论 -
【Python】腾讯云调用API接口获得OCR信息
import osimport refrom tencentcloud.common import credentialfrom tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException# 导入对应产品模块的 client models。from tencentcloud.common.profile.client_profile import ClientProfileim原创 2020-06-03 11:35:11 · 1080 阅读 · 4 评论 -
【Python】Python保存和读取字典
突然发现了一个保存字典很爽的方法,直接用.pkl保存import pickledef save_obj(obj, name): with open(name + '.pkl', 'wb') as f: pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)def load_obj(name): with open(name + '.pkl', 'rb') as f: return pickle.load(f)原创 2020-05-31 23:19:48 · 4484 阅读 · 0 评论 -
【Python】pyUserInput模拟鼠标键盘
安装pyUserInput方法原创 2020-05-27 16:05:33 · 349 阅读 · 0 评论 -
【Flask】搭建服务过程笔记
json中load和loads区别Python Flask Web 框架入门:https://blog.csdn.net/sinat_38682860/article/details/82354342原创 2020-05-26 11:30:13 · 237 阅读 · 0 评论 -
【Anaconda】在命令行输入python后显示Failed calling sys.__interactivehook__
问题描述Python 3.7.6 (default, Jan 8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32Type "help", "copyright", "credits" or "license" for more information.Failed calling sys.__interactivehook__Traceback (most recent call last): Fil原创 2020-05-22 12:06:11 · 1059 阅读 · 3 评论 -
【目标检测】soft-nms的一个大坑+python变量的赋值+函数传引用机制
soft-nms代码如下:def soft_nms(np.ndarray[float, ndim=2] boxes, float sigma=0.5, float Nt=0.3, float threshold=0.001, unsigned int method=0): cdef unsigned int N = boxes.shape[0] cdef float iw, ih, box_area cdef float ua cdef int pos = 0 cd原创 2020-05-17 21:56:25 · 306 阅读 · 0 评论 -
【Pytorch】RuntimeError: one of the variables needed for gradient computation has been modified by
参考:RuntimeError: one of the variables needed for gradient computation has been modified by an inplace o报错RuntimeError: one of the variables needed for gradient computation has been modified by an in...原创 2020-04-06 15:35:36 · 704 阅读 · 0 评论 -
【Python】对含有中文的txt进行读取
with open(filename, 'r', encoding='utf8') as f: # 以下为每一行单独存放在一个str,info为一个list infor = f.readlines() # 也可以全部存放在一个str里面 # infor = f.read()...原创 2020-04-04 20:49:31 · 2064 阅读 · 0 评论 -
【Python】对数据库MongoDB进行增删查改
参考:Python MongoDB | 菜鸟教程# coding:utf-8import pymongo# 连接mongodmyclient = pymongo.MongoClient("mongodb://localhost:27017/")# 列出所有数据集dblist = myclient.list_database_names()print('列出所有数据集:', dbli...原创 2020-04-01 17:16:01 · 237 阅读 · 0 评论 -
【Python】调用腾讯云API接口返回人脸属性信息代码例子
腾讯云的人脸检测文档:https://cloud.tencent.com/document/product/867/32800注意:传入本地图片的话,需要把图片转为base64格式# -*- coding: utf-8 -*-from tencentcloud.common import credentialfrom tencentcloud.common.exception.tencen...原创 2020-04-01 15:28:01 · 674 阅读 · 0 评论 -
【Python】多线程并发共同处理一个大任务代码例子
参考:python多线程执行同一个函数任务之threading、ThreadPoolExecutor.map主要实现的是多个线程同时是完成一个大型任务,代码的思路是把大任务分解,得到每个线程各自需要处理的任务量,然后再把任务函数和任务量分别放入不同线程中如果要换成自己的任务的话,要改的地方:_l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]换成你自己需要处理的总任务...原创 2020-04-01 15:20:45 · 2086 阅读 · 0 评论 -
【Python】断网检测重新启动客户端程序
# encoding: utf-8import osimport timedef restart_Drc(): command = 'taskkill /F /IM DrClient.exe' os.system(command) command = 'taskkill /F /IM DrMain.exe' os.system(command) co...原创 2020-01-21 18:49:23 · 947 阅读 · 0 评论