1、python官网:
Our Documentation | Python.org
range():
random.randint()
sys.exit():
None:
print()返回值为None:None表示没有值
对于所有没有return语句的函数定义,Python都会在末尾加上return None。
2、print()设置end关键字:
如果运行以下程序:
print('Hello')
print('World')
输出是: Hello World
如果运行以下程序:
print('Hello',end=' ')
print('World')
输出是:HelloWorld
3、print()设置sep关键字:
运行print('cats','dogs','mice')
输出是:cats dogs mice
运行print('cats','dogs','mice',sep=',')
输出是:cats,dogs,mice
4、global:(定义全局变量)
5、列表:spam=['cat','bat','rat','elephant']
6、列表下标:
输入spam[0],输出为cat
7、列表负数下标:列表可以用负数作为下标。整数值-1指的是列表中的最后一个下标,-2指的是列表中倒数第二个下标,以此类推。
输入spam[-1],输出为elephant。
8、切片:切片是两个整数。在一个切片中,第一个整数是切片开始处的下标。第二个整数是切片结束处的下标。切片向上增长,直至第二个下标的值,但不包括它。切片求值为一个新的列表值。
spam[1:4]是一个列表和切片(两个整数)。
输入spam[1:3],输出为[‘bat’,'rat']
输入spam[1:-1],输出为['bat','rat']
9、省略下标:
省略第一个下标相当于使用0或列表的开始。省略第二个下标相当于使用列表的长度,意味着切片直至列表的末尾。
输入spam[:2],输出['cat','bat']
输入spam[1:],输出['bat','rat','elephant']
输入:spam[:],输出['cat','bat','rat','elephant']
10、len():获取列表的长度
列表连接(+,*):
输入[1,2,3]+['A','B','C'],输出[1,2,3,'A','B','C']
输入['X','Y','Z']*3,输出['X','Y','Z','X','Y','Z','X','Y','Z']
11、np.stack()
stack()的作用:水平(按列顺序)把数组给堆叠起来
例如:
12、os.path.splitext()
splitext()的作用:分割文件名函数
例如:
13、在list中添加字符串
“ ”.join()的作用:在list中添加字符串
例如:
14、符号//
//:整除的意思,即只取商而不取余数
例如:
15、将list中的内容写到txt文件中
例如1:
结果:
例如2:
结果:
16、一个list中存储的数值为科学计数的数值(即包含e)将其转换为numpy的int型:
np.array(boxes_all[0,:8],dtype=np.int32):boxes_all[0,:8]是一个list
17、矩阵和list的区别,即numpy与list的区别
list各个元素之间有“,”将其分割
numpy的各个元素之间是空格分割
例如:
报错:TypeError: list indices must be integers or slices, not tuple
解决方案:将list类型转换为numpy类型
18、
19、np.arange()与range()的区别(如下图所示)
(1)range()返回值是list,arange()返回值是numpy
(2)range()不需要引入numpy,arange()必须import numpy
20、numpy.random.shuffle打乱数组顺序
21、np.concatenate()拼接numpy的array数组
axis=1表示对应行的数组进行拼接,axis的默认值为0
22.replace()
replace()函数可以由新的字符串替代字符串中的子串,实例如下:
23.os.mkdir()
os.mkdir()函数用于创建目录,在文件存放路径下自动创建文件夹!
import os
File_Path = "F:/VOC_VehicleLicenseRight/"+“0001/”
if not os.path.exists(File_Path):
os.mkdir(File_Path)
24. axis:指定对tensor的哪个维度进行操作
axis=0表示对矩阵的y方向进行操作,axis=1表示对矩阵的x方向进行操作(二维数组)
25.python删除文件
os.remove(filename)
26.python重命名文件
os.rename(oldfilename, newfilename)
27.获取文件路径
os.path.join():在linux与windows下的返回值是不同的,因为windows与linux的路径分隔符不同,分别如下:
28 将列表中的所有元素随机排序
random.shuffle() 返回时列表中的所有元素已经调换顺序
29 获取当前路径
os.getcwd()
30 创建文件夹
os.makedirs()
31 os处理路径的相关接口(具体用法见下图)
os.path.abspath(path):获取path的绝对路径
os.path.isabs(path):判断path是否为绝对路径
os.path.relpath(path,start):获取从start到path的相对路径
os.path.basename(path):获取path的最后一个\\之后的文件名
os.path.dirname(path):获取path的最后一个\\之前的字符串
os.path.split(path):同时分别获取目录名和文件名
os.path.sep:表示正确的文件夹分割斜杠
os.path.getsize(path):获取path的文件的字节大小
os.listdir(path):获取path下的所有文件名
os.path.exists(path):判断path是否存在
os.path.isdir(path):判断path是否是目录名
os.path.isfile(path):判断path是否是文件名
os.chdir(path):更改当前工作目录
os.walk()
32 获取两个list的交集、并集、差集或者用&、|
33原字符串(在有\时如果按一般字符串的形式的话会将'\'作为转义字符,在字符串前面加r则会将'\'直接打印出来)
34 random模块
random.randint(p,q)返回一个p到q之间的随机的int类型的数
35 幂运算(**)
36 条件表达式(三元操作符)【下图中的第113行-118行可由109行-111行代替】
37断言:assert
当assert后面的条件为假的时候,程序自动崩溃并抛出AssertionError异常;当assert后面的条件为真时,继续执行后面的语句
38向列表中添加元素:append(),extend(),insert()
39从列表删除元素:remove(),del,pop()
40 列表的操作符:列表的连接操作符+,列表的重复操作符*
41打印出list的所有内置方法:
42list的count,index,reverse,sort方法[reverse是将列表翻转,sort()默认为升序排列,当sort的参数reverse设置为True时是逆序排列]
43、获取list中的众数
from scipy.stats import mode
lll=[2,3,4,5,3,3,3,6,7,8,3,3,3,3,3,3,3,3,5,5,7]
num=mode(llll)[0][0]
44、将一个list每n个元素分为一组:
ls_diff_each=[ls[i:i + n] for i in range(0, len(ls), n)]
45、迅速获取list中元素出现的次数
from collections import Counter
print(Counter(list_a))
print(Counter(arr).most_common(1))
46、python之多进程,调用多进程的函数只有一个参数
def process(line):
print(line)
from multiprocessing import Pool
if __name__ == '__main__':
p_num=5 #######进程数
para_list=['a','b','c','d','e','f','g']
p = Pool(p_num)
p.map(process,para_list)###para_list是一个list,line是para_list中的一个元素
p.close()
p.join()
47、python之多进程,调用多进程的函数有两个参数
def process(line,each_mp4_imgs):#process有两个参数,line是一个list中的元素,each_mp4_imgs在该函数中保持不变
print(line)
print(each_mp4_imgs)
from multiprocessing import Pool
from functools import partial
if __name__ == '__main__':
p_num=5 #######进程数
para_list=['a','b','c','d','e','f','g']
p = Pool(p_num)
each_mp4_imgs=500
p.map(partial(process, each_mp4_imgs = each_mp4_imgs), para_list)###para_list是一个list,line是para_list中的一个元素
p.close()
p.join()
48、从list中随机选取N个元素
import random
samples = random.sample(list, n)
49、以list中的某个元素分割list
from itertools import groupby
reader=[["***"],[2],["eee"],[3],["rrrr"],["***"],["eeeeeeeee"],["TTTTTT"],["***"],["%%%%%%%%%"]]
result = [list(g) for k, g in groupby(reader, lambda x: x == ['***']) if not k]
50、按照文件名中的数字字符对文件夹中的文件排序,例如文件夹i里面的文件有[rgb_ir_20200623235107_267.jpg、rgb_ir_20200623235107_268.jpg、rgb_ir_20200623235107_269.jpg、rgb_ir_20200623235107_270.jpg、
rgb_ir_20200623235107_271.jpg、rgb_ir_20200623235107_272.jpg],将这些文件按照最后一个下划线后的数字进行排序
folders = sorted(os.listdir(i), key=lambda s: int(s.split("_")[-1].split(".")[0]))
51、dic.setdefault(key,{}).update(dic_frame):向字典的同一个key中添加字典类型的元素
52、dic.setdefault(key,[]).append(list_frame):向字典的同一个key中添加list类型的元素
53、判断.jpg是否为空
54、计算IOU
def compute_iou(gt_box, b_box): ''' 计算iou :param gt_box: ground truth gt_box = [x0,y0,x1,y1](x0,y0)为左上角的坐标(x1,y1)为右下角的坐标 :param b_box: bounding box b_box 表示形式同上 :return: ''' width0 = gt_box[2] height0 = gt_box[3] width1 = b_box[2] height1 = b_box[3] max_x = max(gt_box[2]+gt_box[0], b_box[2]+b_box[0]) min_x = min(gt_box[0], b_box[0]) width = width0 + width1 - (max_x - min_x) max_y = max(gt_box[3]+gt_box[1], b_box[3]+b_box[1]) min_y = min(gt_box[1], b_box[1]) height = height0 + height1 - (max_y - min_y) if width>0 and height>0: interArea = width * height boxAArea = width0 * height0 boxBArea = width1 * height1 iou = interArea / (boxAArea + boxBArea - interArea) else: iou=0 return iou
55、获取list中距离目标值最近的index
import numpy as np target=1632457800 def find_closest(A, target): #A must be sorted idx = A.searchsorted(target) idx = np.clip(idx, 1, len(A)-1) left = A[idx-1] right = A[idx] idx -= target - left < right - target return idx time_ls=[1632456003, 1632456011, 1632456012, 1632456013, 1632456014, 1632456015, 1632456045, 1632456046, 1632456047, 1632456051, 1632456054, 1632456056, 1632456057, 1632456058, 1632456063, 1632456064, 1632456065, 1632456066, 1632456067, 1632456068, 1632456070, 1632456071, 1632456072, 1632456073, 1632456074, 1632456075, 1632456079, 1632456081, 1632456083, 1632456085, 1632456086, 1632456087, 1632456088, 1632456090, 1632456092, 1632456093, 1632456095, 1632456096, 1632456102, 1632456103, 1632456105, 1632456106, 1632456111, 1632456112, 1632456114, 1632456115, 1632456117, 1632456119, 1632456120, 1632456121, 1632456123, 1632456126, 1632456127, 1632456128, 1632456131, 1632456132, 1632456133, 1632456134, 1632456135, 1632456136, 1632456137, 1632456139, 1632456140, 1632456144, 1632456145, 1632456146, 1632456148, 1632456149, 1632456150, 1632456151, 1632456154, 1632456156, 1632456157, 1632456159, 1632456160, 1632456162, 1632456163, 1632456164, 1632456165, 1632456167, 1632456168, 1632456170, 1632456173, 1632456175, 1632456176, 1632456177, 1632456179, 1632456180, 1632456182, 1632456184, 1632456185, 1632456189, 1632456191, 1632456193, 1632456196, 1632456197, 1632456198, 1632456200, 1632456205, 1632456207, 1632456209, 1632456211, 1632456212, 1632456213, 1632456216, 1632456217, 1632456221, 1632456222, 1632456228, 1632456232, 1632456236, 1632456237, 1632456238, 1632456239, 1632456240, 1632456246, 1632456248, 1632456249, 1632456250, 1632456251, 1632456252, 1632456254, 1632456255, 1632456258, 1632456259, 1632456260, 1632456261, 1632456264, 1632456267, 1632456268, 1632456270, 1632456271, 1632456272, 1632456273, 1632456274, 1632456277, 1632456278, 1632456280, 1632456281, 1632456282, 1632456283, 1632456287, 1632456288, 1632456289, 1632456290, 1632456292, 1632456293, 1632456295, 1632456297, 1632456300, 1632456301, 1632456302, 1632456304, 1632456308, 1632456310, 1632456311, 1632456312, 1632456313, 1632456314, 1632456315, 1632456316, 1632456318, 1632456319, 1632456321, 1632456322, 1632456344, 1632456418, 1632456441, 1632456444, 1632456451, 1632456489, 1632456496, 1632456578, 1632456620, 1632456636, 1632456695, 1632456723, 1632456763, 1632456775, 1632456786, 1632456800, 1632456801, 1632456816, 1632456826, 1632456827, 1632456837, 1632456848, 1632456861, 1632456885, 1632456903, 1632456935, 1632459586, 1632460520, 1632460524, 1632460527, 1632460529, 1632460530, 1632460532, 1632460533, 1632460534, 1632460535, 1632460537, 1632460538, 1632460539, 1632460546, 1632460548, 1632460549, 1632460550, 1632460551, 1632460552, 1632460555, 1632460556, 1632460557, 1632460559, 1632460573, 1632460575, 1632460577, 1632460578, 1632460669, 1632460674, 1632460686, 1632460691, 1632460692, 1632460699, 1632460700, 1632460709, 1632460745, 1632460789, 1632460825, 1632460837, 1632460850, 1632460882, 1632460910, 1632460944, 1632460955, 1632460956, 1632460964, 1632460965, 1632460973, 1632460983, 1632460992, 1632461011, 1632461037, 1632461038, 1632461044, 1632461047, 1632461055, 1632461069, 1632461080, 1632461090, 1632461099, 1632461109, 1632461121, 1632461131, 1632461141, 1632461162, 1632461165, 1632461178, 1632461188, 1632461199, 1632461229, 1632461232, 1632461259, 1632461272, 1632461299, 1632461321, 1632461334, 1632461356, 1632461367, 1632461386, 1632461415, 1632461440, 1632461453, 1632542410, 1632542411, 1632542412, 1632542413, 1632542414, 1632542417, 1632542423, 1632542434, 1632542435, 1632542437, 1632542439, 1632542440, 1632542441, 1632542443, 1632542445, 1632542447, 1632542457, 1632542463, 1632542464, 1632542465, 1632542467, 1632542468, 1632542469, 1632542471, 1632542472, 1632542478, 1632542479, 1632542480, 1632542482, 1632542483, 1632542484, 1632542486, 1632542487, 1632542492, 1632542498, 1632542504, 1632542507, 1632542511, 1632542512, 1632542514, 1632542515, 1632542516, 1632542517, 1632542518, 1632542521, 1632542522, 1632542525, 1632542526, 1632542529, 1632542532, 1632542533, 1632542535, 1632542537, 1632542538, 1632542539, 1632542542, 1632542543, 1632542545, 1632542549, 1632542550, 1632542556, 1632542558, 1632542559, 1632542560, 1632542561, 1632542562, 1632542563, 1632542566, 1632542570, 1632542571, 1632542572, 1632542574, 1632542587, 1632542590, 1632542591, 1632542593, 1632542595, 1632542596, 1632542599, 1632542601, 1632542603, 1632542605, 1632542609, 1632542612, 1632542616, 1632542620, 1632542621, 1632542622, 1632542624, 1632542629, 1632542636, 1632542637, 1632542643, 1632542646, 1632542649, 1632542651, 1632542653, 1632542655, 1632542656, 1632542657, 1632542658, 1632542659, 1632542660, 1632542661, 1632542662, 1632542669, 1632542670, 1632542671, 1632542672, 1632542673, 1632542674, 1632542677, 1632542678, 1632542679, 1632542683, 1632542687, 1632542691, 1632542693, 1632542695, 1632542696, 1632542697, 1632542698, 1632542699, 1632542701, 1632542702, 1632542703, 1632542704, 1632542705, 1632542706, 1632542708, 1632542709, 1632542733, 1632542734, 1632542735, 1632542740, 1632542742, 1632542745, 1632542746, 1632542747, 1632542748, 1632542749, 1632542750, 1632542751, 1632542752, 1632542753, 1632542755, 1632542756, 1632542757, 1632542759, 1632542760, 1632542761, 1632542762, 1632542764, 1632542767, 1632542768, 1632542772, 1632542781, 1632542787, 1632542795, 1632542798, 1632543032, 1632543043, 1632543053, 1632543061, 1632543074, 1632543088, 1632543094, 1632543103, 1632543115, 1632543135, 1632543163, 1632543174, 1632543186, 1632543201, 1632543255, 1632543258, 1632543268, 1632543269, 1632543285, 1632543301, 1632543329, 1632543344, 1632543353, 1632543367, 1632543385, 1632543406, 1632543423, 1632543440, 1632543461, 1632543471, 1632543483, 1632543796, 1632543967, 1632544020, 1632548952, 1632548953, 1632548954, 1632548955, 1632548956, 1632548957, 1632548958, 1632548975, 1632548976, 1632548979, 1632548982, 1632548984, 1632548986, 1632548988, 1632548990, 1632548991, 1632548993, 1632548995, 1632548997, 1632548999, 1632549000, 1632549002, 1632549004, 1632549006, 1632549008, 1632549009, 1632549010, 1632549012, 1632549014, 1632549016, 1632549018, 1632549020, 1632549021, 1632549023, 1632549024, 1632549026, 1632549028, 1632549030, 1632549038, 1632549045, 1632549046, 1632549047, 1632549048, 1632549049, 1632549050, 1632549055, 1632549057, 1632549058, 1632549059, 1632549060, 1632549062, 1632549063, 1632549096] A=np.array(time_ls) idx=find_closest(A,target) print(idx) print(time_ls[idx])
56、获取list中所有某个元素的idex
import numpy as np arr = np.array(list) index = np.where(arr==1) print(index[0])
57、将list中的所有元素都减去同一个值
方法一:
a[:] = [x - 13 for x in a]
方法二:
>>> import numpy
>>> array = numpy.array([49, 51, 53, 56])
>>> array - 13
array([36, 38, 40, 43])
58、读取的文本中有汉字时可能会报如下bug:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc8 in position 0: invalid continuation byte
解决方案:
df = open('catering_sale.txt',"r", encoding = 'gb2312')
60、两个list中同一个index的元素相减:
a = [1, 2, 3, 4, 5, 6]
b = list(np.arange(6))
np.array(a) - np.array(b)
list(np.array(a) - np.array(b))#转化成list数组
61、assert 的用法
62、numpy.unique()的用法
63、初始化一个values为列表的字典
from collections import defaultdict
a=defaultdict(list)
64、判断一个变量是否为list类型,如果是list类型则返回该变量,否则将该变量转换为list类型返回
def _isArrayLike(obj): return hasattr(obj, '__iter__') and hasattr(obj, '__len__') a=_isArrayLike([1]) catIds=[1] catIds = catIds if _isArrayLike(catIds) else [catIds] print(catIds)
65、numpy中选取符合条件的数值
66、time模块的函数用法
import time a=time.localtime()###获取当前时间 print(a)
67、filter():filter()函数接收一个函数 f 和一个list,这个函数 f 的作用是对list中的每个元素进行判断,返回 True或 False,filter()根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的新list。
68、instance():用于判断变量类型
a=[9,8,5,3,7] b=isinstance(a,list)###如果a是list类型返回True,否则返回False print(b)
69、capitalize():返回首字母大写的str
70、python 命令行传参argparse实现True|False 【action必须设置为“store_true”】
输出如下:
71、生成器yield
72、urlparse()详解
from urllib.parse import urlparse result=urlparse(url)
详见:爬虫urllib库parse模块的urlparse详解_chengqiuming的博客-CSDN博客_urlparse
73 、使用清华源升级pip3
python3 -m pip install --upgrade pip -i https://pypi.tuna.tsinghua.edu.cn/simple
74、使用清华源安装python包
pip3 install pycocotools -i https://pypi.tuna.tsinghua.edu.cn/simple
75、csv文件的处理
import csv csvPath="D:/DataSet/bfzhao/car_model.csv" f=open(csvPath,"r",encoding="utf-8") for row in csv.reader(f): print(row)
76、zip()的使用
77、python中的异或^
78、将二进制字符串转换为int类型,例如将字符串'11'转换为int类型为数字3
a=int('11',2)
79、将十进制数字转换为二进制字符串,例如数字3转换为二进制位为11
b=bin(3)[2:]
80、格式化打印字典
c={"dog":"jkdhj","pig":"gsjkdbcfd"}
json_body = json.dumps(c, indent=4, ensure_ascii=False)
#####ensure_ascii=False代表正常显示特殊字符
80、python中关于None
if None 相当于 if False
if not None 相当于 if True