python有许多实用函数,合理实用可以大幅精简代码。本篇博文旨在记录一些常用的操作技巧,以便重复使用时快速查阅,会持续进行更新。

whl文件下载地址

Windows:https://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy
Windows+Linux:https://sourceforge.net/projects/scipy.mirror/files/v1.7.2/

读取txt文件

data = np.genfromtxt('./sonar.txt', delimiter=',', usecols=np.arange(0, 60)

通过numpy的genfromtxt来读取txt文件
delimiter 分隔符
usecols 指定读取的列

随机生成正态分布数

生成[0,1)大小为(2,2)的符合正态分布的矩阵

u = np.random.uniform(0, 1, (2, 2))

随机生成不重复的数

产生k个[0,60)的不同随机数

Index = random.sample(range(0, 60), k)

返回列表中最多次出现过的数

cx = max(label_list, key=label_list.count)

返回数组中非零元素的位置

nozero_index = np.nonzero()

这个函数更多的实用案例可参考:
https://www.cnblogs.com/pengzhonglian/p/11613336.html

绘制散点图

导入库:

import matplotlib.pyplot as plt
plt.figure(1)
plt.scatter(x0[:, 0], x0[:, 1], c='r', marker='o', label='类别一') # scatter绘制散点图
plt.scatter(x1[:, 0], x1[:, 1], c='g', marker='o', label='类别二')
plt.xlabel('x轴标签')
plt.ylabel('y轴标签')
plt.title('图片标题')
plt.legend(loc=2)  # 把图例放到左上角
plt.rcParams['font.sans-serif'] = ['SimHei'] # 中文字体显示
plt.savefig('./保存名')# 导出图片保存
plt.show() # 显示图片

关于浅拷贝和深拷贝的冷知识


没有嵌套,copy()即可;
有嵌套,必须copy.deepcopy(变量)

求欧式距离

经常用到,有两种方式实现,一种手写,另一种调用numpy的某接口。
我倾向手写的方式,对结果更容易掌控。

# 计算x,y欧式距离
def dist_cal(x, y):return ((x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2) ** 0.5

洗牌操作shuffle

用于打乱某序列的固定顺序

np.random.shuffle(rand_ch)

求累积和

在轮盘赌算法中常用,累求和序列

q = p.cumsum()

比如 ,这里的p是1,2,3,q就是1,3,6

生成随机数/整数

生成随机数:

np.random.rand()

生成随机整数:

np.random.randint()

括号里可添加范围,默认(0,1]

求列表ind_a中元素等于1的下标

index = np.argwhere(ind_a == 1)

反解包*zip

已知location = [(x1,y1),(x2,y2)]
通过下面的方式将x,y单独分离

x, y = zip(*location)

将一个序列作为索引,另一个序列输出索引值

很实用,很巧妙

ls=[1,2,3,4,5,6,7,8,9,0]#list
index=[2,3,6]#index list
[ls[i]for i in index]

array的部分翻转

翻转[::-1]

a = np.array([[24, 20, 10, 22, 21, 4, 27, 6, 25, 1, 0, 28, 2, 17, 14, 7, 12, 16, 8, 23, 9, 3, 13, 11,19, 18, 26, 5, 15],[24, 20, 10, 22, 21, 4, 27, 6, 25, 1, 0, 28, 2, 17, 14, 7, 12, 16, 8, 23, 9, 3, 13, 11,19, 18, 26, 5, 15]])
a[0,1:4] = a[0,1:4][::-1]

结果:a[0]的20,10,22变为22,10,20

List中每个数都除以某数

直接除会报错,巧妙办法:
每个数都除以10

my_list = [x/10 for x in my_list]

多个列表同时排序

遇到这么一个问题:两个list元素一一对应,一个list进行排序,另一个list上的元素也跟着排序,保持一一对应关系。
下面是我遇到的实际问题场景:
一个list存储文章标题,另一个list存储文章发表时间,根据时间来进行两者同时排序:

title_list = ['文章1标题', '文章2']
time_List = ['2021-2-12', '2020-3-18']title_time = zip(title_list, time_List)
sorted_title_time = sorted(title_time, key=lambda x: x[1])
result = zip(*sorted_title_time)
title_list, title_time = [list(x) for x in result]
print(title_list)
print(title_time)

主要思路:用zip将两者进行打包,排序完之后再用zip*解包。

跳过异常继续运行

这个需求是我在进行爬虫练习时遇到的,有的网站为了防爬虫,会连续性的网站数据中加入某些异常值,导致正常爬虫遇到时会进行报错,从而前功尽弃。
为了防止这种事情发生,就需要通过异常检测的方式来跳过去:

    for item in List:try:# 继续执行的内容except Exception:passcontinue

字符串截取(以截取Link为例)

字符串截取比较常规,遇到这么一个场景:需要从字符串中提取出所有的网页链接,即Link。
可直接调用下面封装好的函数。

# 从a标签中切分出具体文章链接
def split_link(string):start_string = 'http'end_string = '.html'sub_str = ""start = string.find(start_string)# 只要start不等于-1,说明找到了httpwhile start != -1:# 找结束的位置end = string.find(end_string, start)# 截取字符串 结束位置=结束字符串的开始位置+结束字符串的长度sub_str = string[start:end + len(end_string)]# 找下一个开始的位置# 如果没有下一个开始的位置,结束循环start = string.find(start_string, end)return sub_str

获取今天年月日

import time
print(time.strftime("%Y-%m-%d"))

转换array中类型

将numpy中的array序列中的类型进行转换可使用astype
例如:转换成浮点型

X.astype(int)

Matplotlib设置中文

让图例显示中文,全局添加:

import matplotlib.pyplot as pltplt.rcParams['font.sans-serif'] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False

Matplotlib两个子图并列显示

使用subplot控制子图位置,用figsize调整子图大小

plt.figure(figsize=(20, 15))
plt.subplot(2, 2, 1)
for i in range(len(label_pred)):plt.scatter(smile['smile'][i][0], smile['smile'][i][1], color=colors[label_pred[i]])plt.title("原始数据")
plt.subplot(2, 2, 2)
for i in range(len(y)):plt.scatter(smile['smile'][i][0], smile['smile'][i][1], color=colors[y[i]])plt.title("聚类后数据")

Matplotlib子图并列显示/保存组合图

和上面的写法略有区别

# 绘图显示
fig, ax = plt.subplots(1, 3, figsize=(20, 20))
ax[0].imshow(img)
ax[0].set_title("子图标题1")
ax[1].imshow(out_img)
ax[1].set_title("子图标题2")
ax[2].imshow(out_img2)
ax[2].set_title("子图标题3")
plt.show()
fig.savefig(r"组合图名称.png")

统计程序花费时间

import timebegin_time = time.time()
# 所运行程序
end_time = time.time()
print("程序花费时间{}秒".format(end_time-begin_time))

绘制简单折线图并保存

# 绘制折线图
def plot_pic(x, y):plt.plot(x, y, linewidth=1, color="orange", marker="o")plt.xlabel("num_bits")plt.ylabel("ACC (%)")plt.savefig("./result.png")plt.show()

将数据结果写入txt文件

with open(r'./result.txt', mode='a', encoding='utf-8') as f:f.write(str(reward) + "\n")

获取矩阵每行下标

# 获取每行最大值
y_pred = []
for row in y_test:y = np.argmax(row)y_pred.append(y)

通道交换

(3, 320, 640) -> (320, 640, 3)

print(img.shape)  # (3, 320, 640)
print(img.transpose((1, 2, 0)).shape)  # (320, 640, 3)

注意0,1,2表示原序列的索引

Pytorch设置device常用语句

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

用pipreq生成requirements.txt

pipreqs . --encoding=utf8 --force

小脚本:批量修改txt文件

新建一个txt文件,读取原文件每行数据,批量进行添加信息

ff = open(r'D:\Desktop\ailab\task6\pa\submission.txt', 'w')  # 打开一个文件,可写模式
with open(r'D:\Desktop\ailab\task6\pa\pa_result.txt', 'r') as f:  # 打开一个文件只读模式line = f.readlines()for line_list in line:line_new = line_list.replace('\n', '')  # 将换行符替换为空('')line_new = 'cat_12_test/' + line_new + '\n'print(line_new)ff.write(line_new)  # 写入一个新文件中

小脚本:批量给文件加前缀

import ospath = r'F:\jittor提交\test_label'  # 要修改的文件夹路径
pre_name = 'T'  # 修改后的文件名前缀
for filename in os.listdir(path):os.chdir(path)os.rename(filename, pre_name + filename)

小脚本:批量tif转png

注意,转换后并不会将原始tif进行删除,如需删除源文件,可在Linux中运行rm *.tif

import cv2
import numpy as np
import osdef tif_to_png(image_path,save_path):""":param image_path: *.tif image path:param save_path: *.png image path:return:"""img = cv2.imread(image_path, 3)filename = image_path.split('/')[-1].split('.')[0]# print(filename)save_path = save_path + '/' + filename + '.png'cv2.imwrite(save_path, img)if __name__ == '__main__':root_path = r'dataset/preprocessed/test_1024_200_1.0/images/'save_path = r'dataset/preprocessed/test_1024_200_1.0/images'image_files = os.listdir(root_path)for image_file in image_files:tif_to_png(root_path + image_file, save_path)

小脚本:快速筛选出两个文件夹中文件名不一致的文件

import osdef Read_all_images_file_DesignateName():images_file_path = './images'images_file_name = os.listdir(images_file_path)images = []for i in images_file_name:images_file_names = i.split('.')[0]images.append(images_file_names)return imagesdef Read_all_labels_file_DesignateName():labels_file_path = './labelTxt'labels_file_name = os.listdir(labels_file_path)labels = []for l in labels_file_name:labels_file_names = l.split('.')[0]labels.append(labels_file_names)return labelsif __name__  == '__main__':images = Read_all_images_file_DesignateName()labels = Read_all_labels_file_DesignateName()set_images = set(images)set_labels = set(labels)print(set_images^set_labels)

小脚本:批量裁剪图片

将一幅大图裁剪成多张小图:

  • dis:裁剪的长宽
  • leap:每次裁剪窗口滑动的距离(如果小于dis,则裁剪出来的图保有重叠度)
from PIL import Image
import os.path# 指明被遍历的文件夹
rootdir = r'dataset/ceshi/images'
dis = 480
leap = 480
for parent, dirnames, filenames in os.walk(rootdir):  # 遍历每一张图片filenames.sort()for filename in filenames:currentPath = os.path.join(parent, filename)img = Image.open(currentPath)width = img.size[0]height = img.size[1]Flag = Truei = j = 0num = 0for i in range(0, width, leap):for j in range(0, height, leap):box = (i, j, i+dis, j+dis)image = img.crop(box)  # 图像裁剪image.save(r"dataset/ceshi/crop" + '/' + filename.split(".")[0] + "__" + str(num) + ".png")num += 1

python常用函数技巧汇总相关推荐

  1. 纯干货!77个Python常用函数汇总,赶紧收藏!

    Python常用函数: 1. print()函数:打印字符串 2. raw_input()函数:从用户键盘捕获字符 3. len()函数:计算字符长度 4. format(12.3654,'6.2f' ...

  2. pythonencoding etf-8_etf iopv python 代码30个Python常用小技巧

    1.原地交换两个数字x, y =10, 20 print(x, y) y, x = x, y print(x, y) 10 20 20 10 2.链状比较操作符n = 10 print(1 print ...

  3. 机器学习之Python常用函数及模块整理

    机器学习之Python常用函数及模块整理 1. map函数 2. apply函数 3. applymap函数 4. groupby函数 5. agg函数 6. lambda函数 7. rank函数 8 ...

  4. python常用小技巧(一)——百度图片批量爬取

    python常用小技巧(一)--百度图片无限制批量爬取 前言:我们在日常使用(搜壁纸,搜美女--)或者科研项目(图像识别)中经常要批量获取某种类型的图片,然而很多时候我们都需要一个个点击下载,有什么办 ...

  5. python常用函数-python常用函数精讲

    原标题:python常用函数精讲 返回值为bool类型的函数 bool是Boolean的缩写,只有真(True)和假(False)两种取值 bool函数只有一个参数,并根据这个参数的值返回真或者假. ...

  6. python常用函数-python常用函数与用法示例

    本文实例讲述了python常用函数与用法.分享给大家供大家参考,具体如下: 自定义函数实例 # 定义一个函数 def printme( str ): "打印任何传入的字符串" pr ...

  7. Python 常用函数 - Python入门教程

    Python 常用函数 2021 年 3 月 12 日 上午 11:18 [编辑] Python print 函数(一) Python print 函数(二) Python format 函数 Pyt ...

  8. Python常用小技巧(五)——批量读取json文件

    Python常用小技巧(五)--批量读取json文件 前言:其实Python能够批量读取很多文件,这里,本人以json文件为例(json是标注图片时生成的文件,记录有标注的坐标和标签,友情推荐标注图片 ...

  9. python常用小技巧(四)——批量图片改名

    python常用小技巧(四)--批量图片改名 前言:在日常使用中我们需要批量修改图片名字,使用Python的话就可以很快地完成这个目标 一.材料准备 - os 二.程序编写 # -*- coding: ...

最新文章

  1. multisim页面不够大_观赏变出售 捡漏钱不够
  2. python发送短信接口_python发送短信和发送邮件
  3. bzoj 4551: [Tjoi2016Heoi2016]树【并查集】
  4. linux教程期末考试,Linux-期末考试试题8套含答案.doc
  5. 实现linux cp 命令和修改配置文件
  6. [剑指offer][JAVA]面试题第[15]题[二进制中1的个数][位运算]
  7. java中标准输入输出流
  8. java对象怎么创建_java对象是如何创建的
  9. Android 系统(272)---Android中的各种保活
  10. 停止页面定时刷新_Flutter实现倒计时功能、定时任务功能
  11. VRTK之手柄事件监听以及重写StartUsing方法实现与物体的交互
  12. [转载] java中抽象类的定义和使用
  13. CentOS - 安装mysql
  14. 比例化简 详解(C++)
  15. 基于 HTML5 Canvas 的 3D 热力云图效果
  16. java Http请求工具类【post/get】
  17. The server cannot or will not process the request due to something that is perceived to be a client.
  18. pycharm中运行代码
  19. 软件测试--------数据库MySQL 常用sql语句
  20. Android事件分发之ViewGroup篇 -- ViewGroup的dispatchTouchEvent、onTouchEvent、onInterceptTouchEvent之间关系

热门文章

  1. 【BZOJ4373】算术天才⑨与等差数列
  2. fileitem方法_java上传文件(FileItem类的常用方法)
  3. 网管工具——网络人(netman)
  4. 结构化机器学习项目(二)- 机器学习策略(2)
  5. Linux用户权限解析
  6. MATLAB--获取当前系统时间
  7. mmsegmentation使用教程 使用 OpenMMLab 的 MM segmention 下Swin-T 预训练模型 语义分割 推理的记录
  8. AE495 12组视频字幕动画手绘卡通MG图形动画教育文字标题效果工程ae模板
  9. 高纳德箭头_爱糊状-我的意思是莫纳德
  10. 第二十三章 Java线程与操作系统关系