目录
将datetime.datetime.now()获取的当前时间插入MySQL数据库的表中
非运算
not x
反转列表
num = [3, 5, 9, 0, 1, 9, 0, 3]
new_num = list(reversed(num))
根据索引在列表中插入值
list.insert('要插入的值', 索引号)
列表中数据类型转换
比如字符串转整形
list = [int(x) for x in list]
屏蔽警告
import warnings
warnings.filterwarnings('ignore')
线程休眠
import time
在需要休眠的地方写上
time.sleep(xxx)
xxx为对应的时间,单位为秒
获取当前时间
import datetime
datetime.datetime.now()
MySQL数据库
pip install pymysql
delete的时候需要调用commit函数,不然虽然程序执行,但数据库没有变化
将datetime.datetime.now()获取的当前时间插入MySQL数据库的表中
表中字段是DateTime类型
python的datetime.now()返回的时间格式为“2022-09-11 08:00:43.530128”
mysql的datetime格式要求是“2022-09-11 08:00:43”
所以必须转换格式才能把python的时间插入到mysql中
datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
字符串处理
见以下链接:
Python中的各种方法一览-字符串处理_天边一坨浮云的博客-CSDN博客
dict() 函数
创建一个字典。
>>>dict() # 创建空字典
{}
>>> dict(a='a', b='b', t='t') # 传入关键字
{'a': 'a', 'b': 'b', 't': 't'}
>>> dict(zip(['one', 'two', 'three'], [1, 2, 3])) # 映射函数方式来构造字典
{'three': 3, 'two': 2, 'one': 1}
>>> dict([('one', 1), ('two', 2), ('three', 3)]) # 可迭代对象方式来构造字典
{'three': 3, 'two': 2, 'one': 1}
>>>
PriorityQueue
PriorityQueue是优先级队列。越小的优先级越高,会被先取出。
优先队列在插入元素的时候已经对元素做了排序,把最小的元素放在队尾。
Python在对tuple类型作比较时,采用的是按照元素顺序,找到第一个可比较的元素进行比较。
multiprocessing的例子
同时展示了queue和pipe的用法,在image_put, image_get, predict 函数中参数要对应上。
queue获得队列中数据用的是get()方法,pipe获得队列数据用的是recv()方法。
import multiprocessing as mp
pipe = mp.Pipe()
mp.set_start_method(method='spawn') # init
queues = [mp.Queue(maxsize=4) for _ in camera_ip_l]
processes = []
for queue, camera_ip in zip(queues, camera_ip_l):
processes.append(mp.Process(target=image_put, args=(queue, user_name, user_pwd, camera_ip)))
processes.append(mp.Process(target=image_get, args=(queue, camera_ip,pipe[0],)))
processes.append(mp.Process(target=predict, args=(pipe[1],)))
for process in processes:
process.daemon = True
process.start()
for process in processes:
process.join()
Python 3 generator的next方法
g.next() 改为 g.__next__()
g.next()是python 2的用法
查看变量类型
type(变量名)
astype()
转换数组的数据类型。
int32 --> float64 完全ojbk
float64 --> int32 会将小数部分截断
string_ --> float64 如果字符串数组表示的全是数字,也可以用astype转化为数值类型
super()
super() 函数是用于调用父类(超类)的一个方法。
super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。
MRO 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class FooParent(object):
def __init__(self):
self.parent = 'I\'m the parent.'
print ('Parent')
def bar(self,message):
print ("%s from Parent" % message)
class FooChild(FooParent):
def __init__(self):
# super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent),然后把类 FooChild 的对象转换为类 FooParent 的对象
super(FooChild,self).__init__()
print ('Child')
def bar(self,message):
super(FooChild, self).bar(message)
print ('Child bar fuction')
print (self.parent)
if __name__ == '__main__':
fooChild = FooChild()
fooChild.bar('HelloWorld')
python range函数
python range() 函数可创建一个整数列表。
函数语法 range(start, stop[, step])
参数
start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5); stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5 step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)
倒序
for i in range(5, -1, -1)
如果倒序的话最后要定义一个-1表示倒序,并且-1的步长。
引用上级或上上级目录中的文件
上级引用
import sys
sys.path.append("..")
上上级引用
import sys
sys.path.append("...")
删除文件夹下所有文件
def del_file(path_data):
for i in os.listdir(path_data) :# os.listdir(path_data)#返回一个列表,里面是当前目录下面的所有东西的相对路径
file_data = path_data + "/" + i#当前文件夹的下面的所有东西的绝对路径
if os.path.isfile(file_data) == True:#os.path.isfile判断是否为文件,如果是文件,就删除.如果是文件夹.递归给del_file.
os.remove(file_data)
else:
del_file(file_data)
path_data = r"E:\code\practice\data"
del_file(path_data)
复制文件
方法很多,我经常用的是shutil.copy
shutil.copy(source, destination)
判断文件是否存在
import os
os.path.exists(file_path)
图像处理
见以下链接:
Python中的各种方法一览-图像处理_天边一坨浮云的博客-CSDN博客
numpy相关
见以下链接:
Python中的各种方法一览-NumPy_天边一坨浮云的博客-CSDN博客
xls或scv处理
数值处理
见以下链接:
https://blog.csdn.net/ytomc/article/details/131017095?spm=1001.2014.3001.5502
生成新对象
python中对象,赋值后是同一地址,如果是可变对象,对其中一个修改会影响到另一个,如果要生成完全新的对象,应使用deepcopy
import copy
data1=copy.deepcopy(data)
打印
python的print字符串前面加f表示格式化字符串,加f后可以在字符串里面使用用花括号括起来的变量和表达式,如果字符串里面没有表达式,那么前面加不加f输出应该都一样。
读取键盘输入
# -*- coding: utf-8 -*-
import sys
#输入的无论是什么,都会转成字符和字符串
#sys.stdin.readline() 会读取末尾'\n',加.strip(),去掉回车符,同时去掉前后的空格
# 一
#输入一个数
n = int(sys.stdin.readline().strip()) #输入一个元素,并转成整型int
print(n)
# 二
#输入有n行(已知行数n),用for循环,一行有任意个字符字符串都可以
seq = [ ]
for i in range(n):
line = sys.stdin.readline().strip() #line此时是字符串列表,不知line有多少个元素
value = map(int,line.split()) #map(函数,列表)Python2.返回列表,Python3.返回迭代器。
seq += value #合并每一行列表
print(seq)
# 三
#不确定输入有多少行,用while循环
seq = [ ]
while 1:
line = sys.stdin.readline().strip() #line此时是字符串列表,并已去掉前后空格 回车符
if line:
line = map(int,line.split()) #把line的空格元素去掉,转成字符串列表list,并转成整型int
else:
break
seq += line
print(seq)