知识点"/>
python从入门到实践知识点
双引号单引号都表示字符串
修改字符串大小写函数title()、upper()、lower()
连接字符串+
lstrip()删除字符串左端多余的空白
rstrip()删除字符串右端多余的空白
strip()删除字符串两端多余的空白
python2/是整除,python3/不是整除
a**b a^b
str()非字符串值表示为字符串
#注释
import this指导原则
列表[,]
索引为-i,则为倒数第i个元素
列表的修改、增加append()、插入insert(int,)、
根据位置删除del num[i](不保留值)、
弹出列表末尾的元素pop()或者弹出列表指定位置的元素pop(i)(保留值)、
remove()删除指定值的元素(只能删除第一个等于该值的元素)
按字母大小的升序给列表排序sort()
按字母大小的降序给列表排序sort(reverse=True) #sort修改不可恢复
按字母大小的升序给列表临时排序sorted(列表)
按字母大小的升序给列表临时排序sorted(列表,reverse=True) #sorted修改是临时的
反转列表顺序reverse() #不可恢复
列表的长度len()
for循环的使用
注意循环中的代码缩进
range(1,5)生成1~4的数字
list()将一系列数字转换成为列表
range(2,11,2)指定步长为2
创建空列表num=[]
数字列表的相关函数:min(list)、max(list)、sum(list)
列表解析squares=[value**2 for value in range(1,11)] #for语句末尾没有冒号
不区分大小写的测试
使用and和or检查多个条件
判断特定的值是否在列表中,可以使用关键字in
判断特定的值不在列表中,可以使用ont in
注意if和循环中的缩进
在if语句中,将列表名放在条件表达式中,如果列表非空则返回True,否则返回False。
注意if-elif、if-elif-else、if-if-if结构的选择
访问字典中的值
修改字典中的值
添加键值对
删除键值对 del
遍历字典的所有键值对 for key,value in dict.items(): (key和value可以任意取好分辨的名字)
遍历字典的所有键 for key in dict.keys():
for key in dict: 遍历字典时会默认遍历所有的键
遍历字典的所有值 for value in dict.values():
注意:字典的遍历不一定保证顺序
按sorted()顺序遍历字典的键 for key in sorted(dict.keys()):
用set()遍历字典中的值一次(保证不重复) for value in set(dict.values()):
字典列表
列表字典(把列表作为字典的值)(当需要将字典中的键关联到多个值时,可以将字典的键关联到一个列表)
字典字典(把字典作为字典的值)
input()的使用: name=input("Please enter your name:")
print(name) #使用input(),Python把用户的输入读作字符串
int() #使用int()把用户输入的整数数字字符串转化为数值,将数值输入用于计算和比较之前务必将其转化为数值表示
Python2.7用raw_input()来获得用户输入
while循环
标志的使用
braek
continue
Ctrl+C退出无限循环
使用while循环处理列表和字典
在列表之间移动元素
删除包含特定值的所有列表元素
使用用户输入来填充字典
"""文档字符串"""
位置实参(实参需要按照对应形参的顺序输入) #使用默认值,形参列表中必须先列出没有默认值的形参
关键字实参(输入形参—实参对,可以不按照顺序)
可选值函数(把可选的形参默认为空)
Python可以把非空字符串解读为True
函数可以返回任何类型的值,包括列表和字典等较复杂的数据结构
while和函数的结合使用
列表作为函数参数
在函数中修改列表
禁止函数修改列表(通过创建列表的副本作为函数的参数) function_name(list_name[:])
传递任意数量的实参function_name(*parameters)(Python将接受到的实参封装到一个元组中)
结合位置实参和任意数量实参function_name(parameter1,*parameters)
使用任意数量的关键字实参function_name(parameter1,**parameters)(**parameters可以理解为字典的键值对)
将函数存储在模块中:
导入模块import module_name
调用模块中的函数module_name.function_name()
只导入模块中的函数from module_name import function_name()
可用直接调用函数,无需句点
导入模块中的所有函数from module_name import * (注意:最好不要这样做!)
使用as给模块指定别名import module_name as mn
使用as给函数指定别名from module_name import function_name() as fn
创建类:
__init__(self,parament)方法
给属性指定默认值
修改属性的值(直接修改、通过方法修改)
继承:
def __init__(self,parament):
super().__init__(parament) (注意没有self)
给子类定义属性和方法
可以在子类中重写父类的方法(对子类的对象来说,子类的方法会覆盖父类同名的方法)
将另一个类的对象作为类的属性
在一个模块中存储一个类、多个类
从一个模块中导入一个类、多个类
导入整个模块(需要使用句点)
导入模块的所有类(注意:最好不要这样做)
collections模块中的OrderedDict类
random模块中的randint()函数
类名应采用驼峰命名法,即将类名中的每个单词的首字母都大写,而不使用下划线。
实例名和模块名都采用小写格式,并在单词之间加上下划线
/
读取整个文件:
with open("test.txt") as file_object:
contents=file_object.read()
print(contents.rstrip())
(注意:要读取的文件和正在执行的python文件要在同一个目录下。如不在同一目录下,可用绝对路径和相对路径。linux和OS X中用//,windows中用\。通常将绝对路径存储在变量中)
(关键字with在不需要访问文件后将其关闭)
逐行读取:
with open("test.txt") as file_object:
for line in file_object:
print(line.rstrip())
包含文件各行内容的列表:
with open("test.txt") as file_object:
lines=file_object.readlines()
for line in lines:
print(line)
检查特定字符串是否在另一字符串中可用in或not in
写入文件
with open(filename.txt,"w")as file_object:
file_object.write("I love programming!") (注意:写入多行时,要让每个字符串单独占一行,要包含换行符)
(注意:指定的文件存在是Python会将其清空)
写入空文件
指定的文件不存在是Python会创建空文件
附加到文件
Python不会将指定的文件清空
异常:
traceback
try-except
try-except-else
ZeroDivisionError异常
FileNotFoundError异常
ValueError异常
分析单个、多个文本:string_name.split()返回包含文本中所有单词的列表,据此可以统计文本所含的单词数
string_name.count(word_name)返回字符串中指定单词出现的次数
Pass(放在except中什么也不处理)
编写程序时注意哪些错误要报告,哪些不需要
使用json.dump()和json.load()在程序之间共享数据、保存和读取用户生成的数据
(1)import json
filename="numbers.json"
numbers=[1,2,3,4,5,6]
with open(filename,"w")as file_object:
json.dump(numbers,filename)
(2)import json
filename="numbers.json"
with open(filename)as file_object:
numbers=json.load(filename)
print(numbers)
重构:将能正确运行的代码划分为一系列完成具体工作的函数
matplotlib的安装
matplotlib的使用
绘制折线图:
import matplotlib.pyplot as pyp
squares=[0,1,4,9,16,25]
pyp.plot(squares,linewidth=5)#线条加粗
pyp.title("Square Numbers",fontsize=24)#设置标题
pyp.xlabel("Vaule",fontsize=14)#设置横坐标
pyp.ylabel("Square of Value",fontsize=14)#设置纵坐标
#pyp.tick_params(axis="both",labelsize=14)#设置刻度标记大小
pyp.show()
校正图形:
values=[1,2,3,4,5]
squares=[1,4,9,16,25]
pyp.plot(values,squares,linewidths=5)
绘制散点图:
import matplotlib.pyplot as pyp
pyp.scatter(2,4,s=200)
pyp.scatter(3,9)
pyp.title("Squares of Values",fontsize=15)
pyp.xlabel("Values",fontsize=15)
pyp.ylabel("Squares",fontsize=15)
pyp.tick_params(axis="both",which="major",labelsize=15)
pyp.show()
绘制一系列的点:
values=[1,2,3,4,5]
squares=[1,4,9,16,25]
pyp.scatter(values,squares,s=200)
自动计算数据,绘制数量很大的一系列点
values=list(range(1,1001))
squares=[x**2 for x in values]
... ...
pyp.axis([0,1100,0,1100000])
删除数据点轮廓:
pyp.scatter(values,squares,edgecolor="none",s=200) ???
自定义颜色:
pyp.scatter(values,squeres,c="red",edgecolor="none",s=200)
使用颜色映射:
pyp.scatter(values,squares,c=squares,cmap=pyp.cm.Blues,edgecolor="none",s=20) 参数c设置为y值列表,参数cmap设置为颜色
自动保存图表:
将pyp.show()改为pyp.savefig("文件名.png",bbox_inches="tight") 或者先savefig再show
将文件存储到文件名.py所在的目录中。第二个参数指定将图表多余的空白区域裁减掉。
随机漫步:
from random import choice
class RandomWalk():
def __init__(self,num_points=5000):
"""一个生成随机漫步的类"""
self.num_points=num_points
self.x_values=[0]
self.y_values=[0]
def walk(self):
while len(self.x_values)
x_direction=choice([-1,1])
x_distance=choice([0,1,2,3,4,])
x_step=x_direction*x_distance
y_direction=choice([-1,1])
y_distance=choice([0,1,2,3,4])
y_step=y_direction*y_distance
if x_step==0 and y_step==0:
continue
next_x=self.x_values[-1]+x_step
next_y=self.y_values[-1]+y_step
self.x_values.append(next_x)
self.y_values.append(next_y)
模拟多次随机漫步
设置随机漫步的样式:
设置颜色映射来指出随机漫步的先后顺序 ##折线图能使用颜色映射吗???好像不可以
point_numbers=list(range(rw.num_points))
pyp.scatter(rw.x_values,rw.y_values,c=point_numbers,cmap=pyp.cm.Blues,s=15)
绘制起点和终点:
pyp.scatter(0,0,c="green",s=100) ##起点设置为绿色
pyp.scatter(rw.x_values[-1],rw.y_values[-1],c="red",s=100) ##终点设置为红色
隐藏坐标轴:
pyp.axes().get_xaxis().set_visible(False)
pyp.axes().get_yaxis().set_visible(False)
增加点数(注意缩小点的大小)
设置屏幕分辨率的大小:
pyp.figure(dpi=128,figsize=(10,6))
pygal的安装
pygal的使用
使用pygal模拟掷骰子:
绘制直方图:
import pygal
from die import Die
die=Die()
results=[]
for roll_num in range(1000):
result=die.roll()
results.append(result)
frequencies=[]
for value in range(1,die.die_sides+1):
frequency=results.count(value)
frequencies.append(frequency)
hist=pygal.Bar() ##对结果进行可视化(直方图)
hist.title="Result of rolling onr D6 1000 times"
hist.x_labels=['1','2','3','4','5','6']
hist.x_title="Result"
hist.y_title="Frequency of Result"
hist.add("D6",frequencies)
hist.render_to_file("die_visual.svg")
用web浏览器查看生成的SVG文件,输入SVG文件所在的路径
分析CSV文件:
import csv
filename="sitka_weather_07-2014.csv"
with open(filename)as file_object:
reader=csv.reader(file_object)
header_row=next(reader) ##读取第一行的数据
#print(header_row)
#for index,column_header in enumerate(header_row):#打印文件头及其位置
#print(index,column_header)
highs=[] ##提取并读取数据
for row in reader:
highs.append(row[1])
print(highs)
绘sitka2014年全年最高气温和最低气温走势图:
import csv
from matplotlib import pyplot as pyp
from datetime import datetime
##从文件中获取数据
filename="sitka_weather_2014.csv"
with open(filename)as file_object:
reader=csv.reader(file_object)
header_row=next(reader) ##读取第一行的数据
#print(header_row)
#for index,column_header in enumerate(header_row):#打印文件头及其位置
#print(index,column_header)
dates,highs,lows=[],[],[] ##提取并读取数据
for row in reader:
date=datetime.strptime(row[0],"%Y-%m-%d")
dates.append(date)
high=int(row[1])
highs.append(high)
low=int(row[3])
lows.append(low)
print(highs)
##绘制气温图表
fig=pyp.figure(dpi=128,figsize=(10,6))
pyp.plot(dates,highs,c="red",alpha=0.5)
pyp.plot(dates,lows,c="blue",alpha=0.5)
pyp.fill_between(dates,highs,lows,facecolor="blue",alpha=0.1)#给图表区域着色
pyp.title("Daily high and low temperatures - 2014",fontsize=24)
pyp.xlabel("",fontsize=14)
fig.autofmt_xdate()
pyp.ylabel("Temperature(F)",fontsize=14)
pyp.tick_params(axis="both",which="major",labelsize=14)
pyp.savefig("highs_and_lows_2014.png")
pyp.show()
制作交易收盘价走势图:JSON
提取相关数据:
import json
filename="btc_close_2017.json"
with open(filename)as f:
btc_data=json.load(f)
for btc_dict in btc_data:
date=btc_dict["date"]
month=btc_dict["month"]
week=btc_dict["week"]
weekday=btc_dict["weekday"]
close=btc_dict["close"]
print("{} is month {} week{},{},the close price is {} RMB".format(date,month,week,weekday,close))
包含小数点的小数字符串要先转换成float类型,再转化成int类型
绘图:
import json
filename="btc_close_2017.json"
with open(filename)as f:
btc_data=json.load(f)
dates=[]
months=[]
weeks=[]
weekdays=[]
closes=[]
for btc_dict in btc_data:
dates.append(btc_dict["date"])
months.append(int(btc_dict["month"]))
weeks.append(int(btc_dict["week"]))
weekdays.append(btc_dict["weekday"])
closes.append(int(float(btc_dict["close"])))
import pygal
line_chart=pygal.Line(x_label_roration=20,show_minor_x_labels=False)
line_chart.title="收盘价(RMB)"
line_chart.x_labels=dates
N=20 # x轴坐标每隔20天显示一次
line_chart.x_labels_major=dates[::N] #怎么x轴值只显示...???
line_chart.add("收盘价",closes)
line_chart.render_to_file("比特币2017年收盘价走势图.svg")
更多推荐
python从入门到实践知识点
发布评论