对Python进行学习复习总结,没事的时候可以看看。
目录
首先,关于Python的安装,使用Windows系统的可从 Python官方网站 下载安装即可。但是建议直接安装Anaconda,因为Anaconda自带Python,而且自带一些现成库,使用也方便。安装Anaconda从 Anaconda官方网站 下载安装即可。
使用Linux系统的无须额外安装Python,因为市面上主流的Linux发行版都自带Python。
要安装Anaconda的话请从 Anaconda官方网站 下载并打开终端运行安装。 Anaconda的安装可参看 在Ubuntu上部署机器学习环境 。
笔者穷,没有MacOS系统电脑,就不介绍使用MacOS系统安装Python了。
关于编译器,笔者使用Visual Studio Code、PyCharm和Jupyter Notebook。关于Jupyter Notebook的安装可参看 在云服务器中搭建Jupyter Notebook环境 。
一、Python基础知识概要
(一)Python关键字
python的关键字如下:
and | as | assert | break |
class | continue | def | del |
elif | else | except | finally |
for | from | global | if |
import | in | is | lambda |
not | or | pass | raise |
return | try | while | with |
yield |
(二)数据类型
1、数值类型(int、float、complex)
分为整数、浮点数和复数。
2、布尔类型(bool)
布尔类型就是true和false。
3、字符串(str)
字符串长度使用len()获取,如:
print(len("你好呀"))
运行结果为:
3
Process finished with exit code 0
字符串查找使用in和not in,如:
print("你好呀" in "小姐姐你好呀")
运行结果为:
True
Process finished with exit code 0
字符串的切片与索引,如:
a = "小姐姐你好呀"
print(a[0])
print(a[2:3])
print(a[:3])
print(a[2:])
print(a[-1])
运行结果为:
小
姐
小姐姐
姐你好呀
呀
Process finished with exit code 0
字符串常用方法有:
a = "Hello-Hello-Hello"
#大写
print(a.upper())
#小写
print(a.lower())
#首字母大写
print(a.title())
#删除末尾空白
print(a.rstrip())
#删除开头空白
print(a.lstrip())
#删除两边空白
print(a.strip())
#通过给定符号进行分割,分割后成为列表
print(a.split('-'))
#将hello替换成hi
print(a.replace('Hello','hi'))
运行结果为:
HELLO-HELLO-HELLO
hello-hello-hello
Hello-Hello-Hello
Hello-Hello-Hello
Hello-Hello-Hello
Hello-Hello-Hello
['Hello', 'Hello', 'Hello']
hi-hi-hi
Process finished with exit code 0
关于format()方法,如下:
print("男主{}想约女主{},但兜里只有{:.2f}块钱".format("小帅", "小美", 2.5))
print(f"男主{'小帅'}想约女主{'小美'},但兜里只有{2.5}块钱")
运行结果为:
男主小帅想约女主小美,但兜里只有2.50块钱
男主小帅想约女主小美,但兜里只有2.5块钱
Process finished with exit code 0
4、序列类型
(1)列表 (list)
可变、可重复、有序,[ ]
列表的切片索引也是一样,如:
a = [1,2,3,4,5,6]
b = a[:3]
for i in b:
print(i)
运行结果为:
1
2
3
Process finished with exit code 0
(2)元组(tuple)
不可变、可重复、有序 ()
元组存储空间较少,轻量级。
a = (10, 20, 30)
print(a[0])
运行结果为:
10
Process finished with exit code 0
如果非要修改元组的元素,就给存储元组的变量重新赋值,如:
a = (100,200,300)
a = (200,300)
print(a)
for i in a:
print(i)
运行结果为:
(200, 300)
200
300
Process finished with exit code 0
5、散列类型
(1)字典(dict)
可变、key不可重复value可重复、无序 {k:v}
但在Python3.7版本之后有序,可增加、更新、删除元素。
给字典里添加键值对,例如:
a = {'1':'张三','2':'李四'}
print(a)
a['3'] = '王五'
a['4'] = '赵六'
print(a)
运行结果为:
{'1': '张三', '2': '李四'}
{'1': '张三', '2': '李四', '3': '王五', '4': '赵六'}
Process finished with exit code 0
在字典里存储列表,例如:
a = {'1':['张三','李四'],'2':['王五','赵六'],'3':['孙七','周八']}
for key,value in a.items():
print(f"第{key}组:")
for v in value:
print(v.title())
运行结果为:
第1组:
张三
李四
第2组:
王五
赵六
第3组:
孙七
周八
Process finished with exit code 0
修改键值对的值,例如:
a = {'1':'张三','2':'李四'}
print(a)
a['1'] = '王五'
print(a)
运行结果为:
{'1': '张三', '2': '李四'}
{'1': '王五', '2': '李四'}
Process finished with exit code 0
删除键值对,例如:
a = {'1':'张三','2':'李四'}
print(a)
del a['2']
print(a)
运行结果为:
{'1': '张三', '2': '李四'}
{'1': '张三'}
Process finished with exit code 0
遍历字典,例如:
a = {'1':'张三','2':'李四'}
for key in a.keys():
print(f"key:{key}")
for key in a:
print(f"key:{key}")
for value in a.values():
print(f"value:{value}")
for key,value in a.items():
print(f"key:{key}")
print(f"value:{value}")
运行结果为:
key:1
key:2
key:1
key:2
value:张三
value:李四
key:1
value:张三
key:2
value:李四
Process finished with exit code 0
从列表到字典,例如:
a = [1, 2, 3, 4, 5]
b = [10, 20, 30, 40, 50]
c = {a:b for a,b in zip(a,b)}
print(c)
运行结果为:
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
Process finished with exit code 0
插入MonngoDB数据库需用字典结构,例如:
from pymongo import MongoClient
client = MongoClient('mongodb://name:password@ip:27017')
database = client.数据库名
collection = database.集合名
collection.insert_three({"name":"张三","age":18},
{"name":"李四","age":20},
{"name":"王五","age":22})
当访问指定键不存在的值时会报键值错误(KeyError),如果要避免这个报错,可以使用到get()方法,例如:
a = {'1':'张三','2':'李四'}
b = a.get('3','没有这个键值')
print(b)
(2)集合(set)
可变、不可重复、无序 { }
不支持索引操作,可增加、删除元素。
可以借助集合将重复数据去除,例如:
a = [1,2,2,3,3,4]
b = set(a)
print(b)
运行结果为:
{1, 2, 3, 4}
Process finished with exit code 0
上述四种类型特点总结可如下表所示:
数据类型 | 是否可变更 | 是否可重复 | 是否有序 | 符号格式 | 方法 |
---|---|---|---|---|---|
列表 | 可变 | 可重复 | 有序 | [ ] | .append()、.extend()、.remove()、pop()、.sort()、.insert()、.count()、.index()、.reverse() |
元组 | 不可变 | 可重复 | 有序 | ( ) | .count()、.index() |
字典 | 可变 | key不可重复,value可重复 | 无序,Python3.7版本之后有序 | {k:v} | .keys()、.values()、.items()、.get()、.copy() |
集合 | 可变 | 不可重复 | 无序 | { } | .len()、.add()、.update()、.pop() |
如果你学了其他编程语言,会接触到数组这个概念,但在Python的数据类型中没有数组,若要使用数组,就要用到NumPy库,例如:
import numpy
a = numpy.array([1,2,3,4,5,6])
print(a)
print(a[1:3])
#全是0的向量
a = numpy.zeros((3,3),dtype='float64')
print(a)
#全是1的向量
a = numpy.ones((3,3),dtype='int')
print(a)
#全是指定数字的向量
a = numpy.full((3,3),7,dtype='int')
print(a)
#线性序列
a = numpy.arange(1,10,2)
print(a)
#均匀序列
a = numpy.linspace(1,10,10)
print(a)
#单位矩阵
a = numpy.eye(3)
print(a)
#单位矩阵
a = numpy.empty(3)
print(a)
运算结果为:
[1 2 3 4 5 6]
[2 3]
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
[[1 1 1]
[1 1 1]
[1 1 1]]
[[7 7 7]
[7 7 7]
[7 7 7]]
[1 3 5 7 9]
[ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
[1. 1. 1.]
Process finished with exit code 0
数组与列表的区别:
关于数学运算方面,如下,列表是复制,数组是做乘法。
import numpy
a = [1, 2, 3, 4, 5]
b = numpy.array(a)
print(a*2)
print(b*2)
运算结果为:
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
[ 2 4 6 8 10]
列表只能存储一维数据,数组能存储多维数据,例如:
import numpy
a = numpy.array([[1,2],[3,4],[5,6]])
print(a)
运算结果为:
[[1 2]
[3 4]
[5 6]]
Process finished with exit code 0
(三)循环语句和条件语句
1、for循环
for循环生成列表值得平方,例如:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b = [i**2 for i in a]
print(b)
运行结果为:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Process finished with exit code 0
for循环有时候和range()函数搭配,例如:
for i in range(1, 3):
print(i)
运行结果为:
1
2
Process finished with exit code 0
2、while循环
while循环可搭配continue和break来弄,例如:
a = 0
while a < 10:
a += 1
if a % 2 == 0:
continue
print(a)
if a == 5:
break
print(a)
运行结果为:
1
1
3
3
5
Process finished with exit code 0
从别处摘抄的运用了while、for、if语句的程序,用户登录认证,如下:
accounts = {}
f = open("account.db","r")
for line in f:
line = line.strip().split(",")
accounts[line[0]] = line
print(accounts)
while True:
user = input("Username:").strip()
if user not in accounts:
print("该用户未注册。")
continue
elif accounts[user][2] == "1":
print("该用户已被冻结。")
continue
count = 0
while count < 3:
pwd = input("Password:").strip()
if pwd == accounts[user][1]:
print("登录成功。")
exit("再见")
else:
print("密码错误。")
count +=1
password = input("请输入密码:").strip()
3、if语句
if语句的if-elif-else结构,例如:
age = 18
if age <= 18:
print("未成年")
elif age <= 65:
print("成人")
else:
print("老年")
运行结果为:
未成年
Process finished with exit code 0
还有三元操作符的写法,例如:
x,y = 3,5
small = x if x<y else y
print(small)
运行结果为:
3
Process finished with exit code 0
4、match语句
python3.10引入match,例如:
match http_request.status:
case 400:
print("Bad Request")
case 404:
print("Not Found")
#变量名_为通配符,确保match能匹配成功
case _:
print("Unknown Error")
match http_request_status:
case 400|403|404:
print("Bad request")
case 500 or 501 or 503:
print("Server error")
(四)函数与类
1、传递任意数量实参
在定义函数时使用的参数是形参,在调用函数时传递的参数是实参。
如果不知道函数需要接受多少个实参,形参这边可使用*args和**args(字典),例如:
def names(*name):
print(name)
names("Ram","Shyam","Hari")
def namess(name,age,**args):
args["name"]=name
args["age"]=age
return args
print(namess("Ram", 20))
运行结果为:
('Ram', 'Shyam', 'Hari')
{'name': 'Ram', 'age': 20}
Process finished with exit code 0
2、匿名函数
匿名函数相对简洁,例如:
sum = lambda a,b:a+b
print(sum(10,20))
add = lambda a:a+1
print(add(10))
运行结果如下:
30
11
Process finished with exit code 0
闭包是一种特殊的内嵌函数,内部函数对外层非全局作用域的变量进行引用。
3、关于类
可认为首字母大写的名称指的是类,小写的名称指的是根据类创建的实例。
类名一般才用驼峰命名法,每个单词首字母大写。实例名和模块民一般采用小写,单词之间加下划线。
私有变量,加_,如_secreCount=1,私有方法,如def _foo(self)。
类的继承、多态和封装,例如:
class Human:
_name = '人'
def __init__(self, age):
self.age = age
def say(self):
print(f"我是{self._name}类,我有{self.age}岁数")
class Man(Human):
def __init__(self, name, age):
super().__init__(age)
self.name = name
print('我是男人')
def _hello(self):
print(f"我叫{self.name},年龄为{self.age}")
class Woman(Human):
def __init__(self, name, age):
super().__init__(age)
self.name = name
print('我是女人')
def _hello(self):
print(f"我叫{self.name},年龄为{self.age}")
if __name__ == '__main__':
human = Human(20)
human.say()
man = Man('张三', 20)
man._hello()
woman = Woman('李四', 20)
woman._hello()
运行结果为:
我是人类,我有20岁数
我是男人
我叫张三,年龄为20
我是女人
我叫李四,年龄为20
Process finished with exit code 0
关于静态方法和类方法,静态方法()里不写self,类方法使用类名直接访问的方法,例如:
@staticmethod
def method():
pass
@classmethod
def cm(cls):
pass
(五)异常和代码调试
1、异常
处理异常所用到的关键字为try、else、except和finally,例如:
try:
with open('test.txt', encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
print("没有找到文件")
else:
print(contents)
finally:
print("不管有没有异常都会执行")
运行结果为:
没有找到文件
不管有没有异常都会执行
Process finished with exit code 0
抛出异常可使用关键字raise,例如:
raise Exception('error message')
2、代码调试
对于程序在正常运行时遇到的错误、用户的错误,可使用抛出异常处置。如果是针对程序员的错误,可使用assert断言。
使用assert来检查一个条件是否为真。如果条件为假,那么assert会触发一个AssertionError。用于测试,代码前加assert,例如:
a = 11
assert isinstance(a, int) and a < 10, "a不小于10"
运行结果为:
Traceback (most recent call last):
File "demo.py", line 2, in <module>
assert isinstance(a, int) and a < 10, "a不小于10"
AssertionError: a不小于10
Process finished with exit code 1
引入日志的话要使用logging库,引入如下:
import logging
logging.basicConfig(filename='aaa.txt',level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
日志函数级别用法如下:
级别 | 日志函数 | 描述 |
---|---|---|
调试(debug) | logging.debug() | 用于记录详细的调试信息 |
信息(info) | logging.info() | 用于记录程序运行时的正常信息 |
警告(warning) | logging.warning() | 用于记录潜在的问题或未来的变化 |
错误(error) | logging.error() | 用于记录由于更严重的问题而导致程序不能按预期运行的情况 |
临界(critical) | logging.critical() | 用于记录非常严重的错误,这些错误通常会导致程序无法继续运行 |
二、Python的办公自动化
首先在Windows系统中,可将写好的Python代码转换成可执行的程序,方便不懂计算机的同事双击自动化运行,实现办公自动化。实现上述过程需要使用pyinstaller库,安装pyinstaller命令如下:
pip install pyinstaller -i https://mirrors.aliyun.com/pypi/simple
写好的Python代码后缀为.py,输入如下命令将其生成为.exe,双击可运行:
pyinstaller -F test.py
其次,办公嘛分为三大项:Word、PPT和Excel,使用Python进行办公自动化就为通过Python来处理Word、PPT和Excel办公。
(一)PDF
操作PDF使用PyPDF2库,使用命令安装此库:
pip install pypdf2 -i https://mirrors.aliyun.com/pypi/simple
使用PyPDF2库对PDF文档提取文本操作简单示例如下:
from PyPDF2 import PdfReader
pdffile = open(r'C:\Users\AAA\Desktop\中国养老行业未来报告.pdf', 'rb')
reader = PdfReader(pdffile)
print(f"这个PDF文档有{len(reader.pages)}页")
pagefile = reader.pages[0]
text = pagefile.extract_text()
print(text)
pdffile.close()
运行结果如下:
这个PDF文档有67页
中国养老行业未来
医康养一体化
2023.12
Process finished with exit code 0
在工作中使用较多的就是将PDF文件转化为Word格式文件,简单示例如下:
from pdf2docx import Converter
cv = Converter(r'C:\Users\AAA\Desktop\中国养老行业未来报告.pdf')
cv.convert(r'C:\Users\AAA\Desktop\中国养老行业未来报告.docx', start=0, end=None)
cv.close()
最后引用推荐个Github上将文献CAJ文件转换为PDF文件的GitHub - caj2pdf/caj2pdf: Convert CAJ (China Academic Journals) files to PDF. 转换中国知网 CAJ 格式文献为 PDF。佛系转换,成功与否,皆是玄学。
这个作者写的挺好,大家可以看看学习。
(二)Word
Python的Word办公自动化在实际工作中笔者没有遇到,猜想可能要和AI一起用。笔者还没学会LangChain,等会了之后联用再更新这节。
(三)PPT
Python的PPT办公自动化在实际工作中笔者从来没有遇到过,感觉PPT还是要自己设计或者AI设计。但既然大家看了我这篇博客,不水大家,就推荐几个好用的PPT模板网站给大家:
ChatPPT_AI一键对话生成PPT_智能排版美化-必优科技智能PPT(大家如果购买的话麻烦输入下我的共创码哦,3036873,然后我们双方都双方获赠1个月VIP)
PPT超级市场官网-免费、优质、高效、安全的PPT下载和定制
PPT模板_PPT模版免费下载_免费PPT模板下载 -【第一PPT】
PPT模板免费下载_精美免费PPT模板下载 -【优品PPT】
主题PPT模板_热门PPT图示模板_精美PPT图表下载「iSlide网站」
(四)Excel
Python的Excel办公自动化使用到两个库:openpyxl和pandas。安装这两个库使用如下命令:
pip install openpyxl pandas -i https://mirrors.aliyun.com/pypi/simple
然后Excel进行表格存储时除了常见的.xlsx格式外,还有.csv等格式。如果需要处理CSV格式文件,还用到csv这个库。csv库无需额外安装。分析CSV文件头例如:
import csv
file = 'D:\aaa.csv'
with open(file) as f:
reader = csv.reader(f)
header = next(reader)
print(header)
Python办公用到的两个库,调整Excel表格格式、合并解除单元格、排序查找替换、绘制Excel图表等操作大多数情况使用openpyxl库。实现Excel函数计算、进行Excel数据分析等操作大多数情况使用pandas库。
1、openpyxl库的使用
openpyxl库在我的理解通常侧重于表格格式设置和美化,如字体设置、对齐设置、行高列宽设置、图表绘制设置等等。
在插入数据、字体边框设置、制作表格等例如:
from openpyxl import Workbook
from openpyxl.styles import Alignment,PatternFill,Font,Border,Side
import datetime
wb = Workbook()
ws = wb.active
# 给单元格A1赋值
ws['A1'] = "学习呀"
a1 = ws['A1']
# 设置单元格对齐方式为左对齐
a1.alignment = Alignment(horizontal='left')
# 合并单元格A2和A3
ws.merge_cells('A2:C2')
a2 = ws['A2']
# 给单元格A2赋值时间
a2.value = datetime.datetime(2024,5,14,11,35,0)
# 设置单元格A2的背景颜色
a2.fill = PatternFill(fgColor='FF0000', fill_type='solid')
# 设置单元格A2的字体
a2.font = Font(name='微软雅黑', size=12, bold=True,color='FFFFFF')
# 设置单元格A2对齐方式为居中
a2.alignment = Alignment(horizontal='center', vertical='center')
rows = [
['人员信息表','',''],
['姓名', '年龄', '性别'],
['张三', 18, '男'],
['李四', 19, '女'],
['王五', 20, '男'],
['赵六', 21, '女'],
['孙七', 22, '男'],
]
# 循环写入数据
for row in rows:
ws.append(row)
# 设置单元格对齐方式、字体、背景颜色、边框
for col in ws["A3":"C9"]:
for r in col:
r.alignment = Alignment(horizontal='center', vertical='center')
r.font = Font(name='微软雅黑', size=12, bold=True,color='FFFFFF')
r.fill = PatternFill(fgColor='5A1216', fill_type='solid')
r.border = Border(left=Side(border_style='thin', color='000000'),
right=Side(border_style='thin', color='000000'),
top=Side(border_style='thin', color='000000'),
bottom=Side(border_style='thin', color='000000'))
ws.merge_cells('A3:C3')
a3 = ws['A3']
a3.font = Font(name='微软雅黑', size=12, bold=True,color='FFFFFF')
wb.save(r'C:\Users\AAA\Desktop\test.xlsx')
运行结果为:
在图表绘制设置等例如:
from openpyxl import Workbook
from openpyxl.chart import BarChart,Reference
wb = Workbook()
ws = wb.active
rows = [
['时间','数值'],
['2024-01-01',400],
['2024-01-02',300],
['2024-01-03',200],
['2024-01-04',100],
['2024-01-05',500],
['2024-01-06',600],
['2024-01-07',700],
['2024-01-08',800],
['2024-01-09',900],
['2024-01-10',1000],
['2024-01-11',1100],
]
for row in rows:
ws.append(row)
chart = BarChart()
# 设置数据
data = Reference(ws,min_col=2,min_row=1,max_col=2,max_row=11)
chart.add_data(data,titles_from_data=True)
chart.title = '时间数值柱状图'
# 设置样式1-48
chart.style = 10
chart.x_axis.title = '时间'
chart.y_axis.title = '数值'
ws.add_chart(chart,'A12')
wb.save(r'C:\Users\AAA\Desktop\test.xlsx')
运行结果为:
openpyxl库也可以用作Excel函数计算,此操作为在Python里写公式传给Excel里运行,例如:
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
rows = [
['数值1','数值2','求和'],
[12,23],
[34,45],
[56,67],
]
for row in rows:
ws.append(row)
for r in range(2,5):
ws["C"+str(r)] = "=SUM(A"+str(r)+":B"+str(r)+")"
wb.save(r'C:\Users\AAA\Desktop\test.xlsx')
运行结果为:
2、pandas库的使用
首先,是pandas库与openpyxl库之间相互转换配合使用,示例如下:
import pandas as pd
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows
data = pd.read_excel(r'C:\Users\ljf15\Desktop\test.xlsx')
wb = Workbook()
ws = wb.active
for r in dataframe_to_rows(data, index=False, header=True):
ws.append(r)
wb.save(r'C:\Users\AAA\Desktop\test1.xlsx')
其次pandas库有两种数据结构,分别为Series、DataFrame。
Series是创建一维数组,包含索引。
DataFrame是创建二维表格,为Excel表格数据结构,示例如下:
import numpy as np
import pandas as pd
data = pd.DataFrame(np.arange(9).reshape(3,3),index=['列1','列2','列3'],columns=['行1','行2','行3'])
print(data)
运行结果为:
行1 行2 行3
列1 0 1 2
列2 3 4 5
列3 6 7 8
Process finished with exit code 0
pandas库在我的理解通常侧重于数据分析,Excel常用的函数如vlookup、sumproduct、sumif、countif函数在pandas库中转化如下:
vlookup函数:
pandas.merge(表1,表2,on="字段名称",how=left)
其中on为使用哪个列字段作为表1和表2的拼接,how用于指明是表1为主表还是表2为主表。
sumproduct函数:
import pandas
data = pandas.DataFrame({'数值1':[1,2,3,4,5],'数值2':[1,2,3,4,5],'数值3':[1,2,3,4,5]})
data['数值相乘后总和'] = data['数值1']*data['数值2']*data['数值3']
a = data['数值相乘后总和'].sum()
print(a)
sumif函数:
import pandas
data = pandas.DataFrame({'数值1':[1,2,3,4,5],'数值2':[1,2,3,4,5],'数值3':[1,2,3,4,5]})
a = data[data['数值1']>4]['数值3'].sum()
print(a)
countif函数:
import pandas
data = pandas.DataFrame({'编号':['A1','A2','A3','A4','A5'],'性别':['男','男','女','男','女']})
a = data.groupby('性别')['编号'].count()
print(a)
三、Python数据分析可视化:Matplotlib库
Matplotlib库用来绘制图形,需要运行pip安装matplotlib包,使用如下命令:
pip install matplotlib -i https://mirrors.aliyun.com/pypi/simple
在使用Matplotlib库进行绘图时遇到中文字体无法显示的情况,可参看这篇文章关于Matplotlib作图时中文字体无法显示问题 。
(一)绘制图形
1、绘制柱状图
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname='C:\Windows\Fonts\simhei.ttf')
plt.xlabel("X轴", fontproperties=font)
plt.ylabel("Y轴", fontproperties=font)
plt.title("柱状图示例", fontproperties=font)
x = [1, 2, 3, 4, 5]
y = [5, 4, 3, 2, 1]
plt.bar(x, y, width=0.5, color="blue")
#绘制图像网格
plt.grid()
plt.show()
运行结果如下:
2、绘制折线图
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname='C:\Windows\Fonts\simhei.ttf')
plt.xlabel("X轴", fontproperties=font)
plt.ylabel("Y轴", fontproperties=font)
plt.title("折线图示例", fontproperties=font)
x = [1, 2, 3, 4, 5]
y = [5, 4, 3, 2, 1]
z = [2, 3, 4, 5, 6]
plt.plot(x, y, label="x,y",color="red", linewidth=2, linestyle="--")
plt.plot(x, z, label="x,z",color="blue", linewidth=2)
plt.legend(loc="upper left")
#绘制图像网格
plt.grid()
plt.show()
运行结果如下:
3、绘制散点图
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import numpy as np
font = FontProperties(fname='C:\Windows\Fonts\simhei.ttf')
plt.xlabel("X轴", fontproperties=font)
plt.ylabel("Y轴", fontproperties=font)
plt.title("散点图示例", fontproperties=font)
plt.style.use('seaborn')
x = np.random.randn(20)
y = np.random.randn(20)
plt.scatter(x,y,s=100)
plt.show()
运行结果如下:
4、绘制直方图
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import numpy as np
font = FontProperties(fname='C:\Windows\Fonts\simhei.ttf')
plt.xlabel("X轴", fontproperties=font)
plt.ylabel("Y轴", fontproperties=font)
plt.title("直方图示例", fontproperties=font)
data = np.random.randn(10000)
plt.hist(data, bins=30,edgecolor='black')
plt.show()
运行结果为:
(二)绘制图形示例
记录了两个使用Matplotlib库进行画图的,详情请看链接记录两个Matplotlib画图代码-CSDN博客
结尾
混合编程:使用Pythran库将Python转换为C++。
pythran -e demo.py -o demo.hpp
LRU算法:Least Recently Used
from functools import lru_cache
@lru_cache()
结尾部分推荐几个Python学习网站: