1. Python特点
- Python面向对象、解析性的语言
- 几种解析器:
- CPython:C语言解析Python语言的解析器
- Jpython:Java语言解析Python语言
- IronPython:用C#(.net平台)解析
- PyPy:是使用Python语言解析
- Python的应用广,在科学计算、自然语言处理、图形图像处理、脚本开发、Web应用
- Python几种版本:
- Python2.X
- Python3.X
- Python并没有做到向下兼容,了解两个版本的区别和联系
- 能够无缝的改进Python2.x的代码d到Python3.x中
2. Python基础版本的安装
-
Python.org
-
目前版本
- 3.8.0
- 3.7.8
- 3.6.8(目前使用)
- 2.7.17
-
Java语言——.java—–jar包——mvn repo—–mvn install/uninstall
-
Python——-.py——-.whl轮子文件—pip install—pip uninstall
-
pip的命令
- pip install package
- pip uninstall package
- pip list展示安装的包
- pip install -U 更新方式安装
3. Anaconda数据科学环境的安装
-
IDE–集成开发环境–Eclipse、IDEA需要加载JDK-Scala
-
大数据hadoop-spark—–CDH(各种大数据组件)
-
数据科学环境:
- Anaconda是数据科学开发环境
- 包含了基础的python的环境
- 在原来的Python的基础上增加了180+多个工具包
-
安装:
- windows安装,直接下一步下一步,遇到需要打钩的地方尽量打上
-
Anaconda中有哪些组件?
- Anaconda-Navigiter
- Anaconda-Prompt
- Anaconda-Ipython–增强式的Python–语法高亮等等—仍然不方便
- Anacodna**-jupyternotebook**
- jupyter notebook是一个以web程序启动web网页交互式的书写代码的平台
- 底层基于ipython的
- 两种打开方式:
- 1-界面的点击方式
- 2-jupyter notebook方式
- 后缀名:.ipynb
- 可以将ipynb的文件拖拽到jupyternotebook中启动交互式编写代码
- Anaconda-Spyder
- IDE
4. 通过Pycharm和Anaconda的整合
-
安装Pycharm—jetBrain公式
-
安装Anaconda
-
第一步:建议大家更改环境变量
-
第二步:更改解析器Interpertor
-
第三步:创建项目
- 创建项目的过程中需要指定解析器
-
第四步:写代码
-
#-*- coding: utf-8 -*- # @Time : ${DATE} ${TIME} # @Author : Turing # @Email : load # @File : ${NAME}.py
-
-
基础代码:
-
print函数在Python2和Python3的区别
-
#-*- coding: utf-8 -*- # @Time : 2022/01/25 10:18 # @Author : Turing # @Email : load # @File : 1.0HelloWorld.py # python2中print是语句,既可以加括号也可以不加括号 # python3中print是函数,必须加括号 # print "HelloWorld" print("HelloWorld")
-
-
conda
- 安装包:pip install conda install
- 卸载包: pip unistall conda uninstall
- 更新的方式安装包:pip install -U conda install -U
- 查看包:pip list conda list(可以查看哪些是pip安装的,那些是conda安装的)
-
Conda命令可以创建独立的Python的沙箱环境
- 在Python3.6中创建了一个Python2.7
- create -n create envName python==2.7.0
- source active envName
- soucre deactive envName
5. Python的基础数据类型
-
编码和解码
-
import sys print(sys.getdefaultencoding()) # ascii表示的字符有限(中文) utf-8(unicode format 8 bytes# ) print("Turing".encode("utf-8")) # 输出:b'\xe5\x85\xac\xe4\xbc\x97\xe5\x8f\xb7\xe4\xba\x94\xe5\x88\x86\xe9\x92\x9f\xe5\xad\xa6\xe5\xa4\xa7\xe6\x95\xb0\xe6\x8d\xae' print(b'\xe5\x85\xac\xe4\xbc\x97\xe5\x8f\xb7\xe4\xba\x94\xe5\x88\x86\xe9\x92\x9f\xe5\xad\xa6\xe5\xa4\xa7\xe6\x95\xb0\xe6\x8d\xae'.decode("utf-8")) print("Turing".encode("gbk")) # 输出:b'\xb9\xab\xd6\xda\xba\xc5\xce\xe5\xb7\xd6\xd6\xd3\xd1\xa7\xb4\xf3\xca\xfd\xbe\xdd' print(b'\xb9\xab\xd6\xda\xba\xc5\xce\xe5\xb7\xd6\xd6\xd3\xd1\xa7\xb4\xf3\xca\xfd\xbe\xdd'.decode("gbk"))
-
导包
-
import requests as re get = re.get("https://www.fivedata.cn") print(get.url) print(get.encoding) print(get.text) #sin(x) import math print(math.sin(0)) #0 from math import sin print(sin(0)) from math import sin as f print(f(0)) import numpy as np print(np.random.randn(3,3)) # [[ 1.22524688 1.40990719 1.49014802] # [-1.3915769 -0.50625637 -0.38625091] # [-1.39770585 -1.52630576 -0.5186793 ]]
-
数据类型
-
# python理解为弱类型的语言,数据类型是不需要程序员指定,系统会自动判断 a = 10.0 print(a) print(type(a)) # <class 'float'> print(id(a)) #在堆栈中的地址 print(id(10.0)) print(id(a)==id(10.0)) b = "string" print(b) print(type(b)) # <class 'str'> c = complex(1, 2) # 1+2j print(c.real) # 1 print(c.imag) # 2 print(c ** 2) # 单目运算符 # + - *乘法 /除法 //整除 **幂 %取模 a = 3 b = 5 print(a + b) print(a - b) print(a / b) print(a // b) print(a % b) print(a ** b) print(a * b) # 双目运算符 # += -= *= /= %= **= //= a += b a -= b a *= b a /= b a //= b a %= b a **= b print(a) # & 按位与 | 按位或 ^按位异或 <<左移 >> 右移 # 8421 a = 5 # 0101 b = 3 # 0011 print(a & b) # 0001 1 print(a | b) # 0111 7 print(a ^ b) # 0110 6 print(a << 1) print(a << 2) print(a >> 1) apple = 'apple' bnana = "bananan" banana_ = '''\ This is apple! This is banana!\ ''' print(apple) print(type(apple)) print(bnana) print(type(bnana)) print(banana_) print(type(banana_)) print(3.1415e2) #e表示10 import math print(math.exp(1))
6. 输入和输出
-
输入
-
# # raw_input将数据进行原样的输入----都是str类型 # # input 输入的类型原样的输入-----如果输入的是数值输出的就是对应的类型 # # 否则input输入的是字符类型的话必须加引号 # # age = raw_input("Please input your age:") # # print(age) # # print(type(age)) # age = input("Please input your age:") # print(age) # print(type(age)) #python3中输入的语句合二为一input和python2的raw_input是一致的 input1 = input("please input your age:") print(input1) print(type(input1))
-
输出
-
name="zhangsan" age=13 print("name is:",name,"age is:",age) print("name is:"+name+"age is:"+str(age)) print("name is:{},age is:{}".format(name,age)) print("name is:{0},age is:{1}".format(name,age)) print("name is:{pig},age is:{pear}".format(pig=name,pear=age)) print("name is:%s,age is:%d"%(name,age))
-
随机数的产生
-
为什么需要随机数?因为获取现实 的数据是非常困难的,可以模仿现实的数据去产生新数据
-
产生一个简单的随机数
-
产生一个符合正态分布的随机数
-
产生一个符合卡方分布的随机数
-
import random # - 产生一个简单的随机数 print(random.random()) print(random.randrange(1,10)) # - 产生一个符合正态分布的随机数 import numpy as np print(np.random.randn(3,3)) # [[-0.65330669 -2.17752451 -0.59458216] # [-1.25848013 1.06000312 -0.21712177] # [-1.5914388 0.59092913 0.56820017]] # - 产生一个符合卡方分布的随机数 # df叫做自由度--越大越接近于正态分布 print("chisuare test:\n",np.random.chisquare(3,(3,3))) print("chisuare test:\n",np.random.chisquare(df=3,size=(3,3)))
-
7. Python的数据结构
-
列表
-
字典
-
元祖
-
集合
-
代码:
-
# list列表-tuple元祖-dict字典-set集合 # list列表--根据[]创建,根据下标查询、更改、删除等操作,元素是异质的 # 1-创建 l1 = [1, 2, 3, 4, 5] print(l1) print(type(l1)) # 2-更新 print("location 0 value is:", l1[0]) l1[0] = "apple" print("list set is:", l1) # 3-增加 l1.append("banana") print(l1) # 4-删除 del l1[5] print(l1) # tuple元祖---根据()创建,根据下标查询,但是不能根据下标更改、删除等操作 # 1-创建 t1 = (1, 2, 3, 4, 5,"apple") print(t1) print(type(t1)) # 2-更新 print(t1[0]) # t1[0]="apple"#TypeError: 'tuple' object does not support item assignment # 3-增加 # 4-删除 # TypeError: 'tuple' object doesn't support item deletion # del t1[0] # dict字典--根据{}创建,根据key获取value,增加或删除value的信息 # 1-创建 pear_ = {"apple": 1, "pear": 2} print(pear_) # 2-更新 pear_["apple"]=100 print(pear_) # 3-增加 pear_["banana"]=1000 print(pear_) # 4-删除 del pear_["banana"] print(pear_) # set集合--集合无序性-互异性-唯一性 # 1-创建 s1 = {1, 2, 3, 4} print(s1) print(type(s1)) # 2-更新 ls1=list(s1) print(ls1) # 3-增加 s1.add("apple") print(s1) # 4-删除 s1.remove("apple") print(s1)
8. Python的列表
-
list
-
切片操作:
-
#创建 l1 = [1, 2, 3, 4] l2 = list((1,2,3,4)) l3 = list({1,2,3,4}) l4 = list({1:"apple",2:"banana",3:"ok",4:"hello"}) print(l1) print(l2) print(l3) print(l4) num=range(10) print(num)#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] range(0, 10) print(type(num))#<type 'list'> <class 'range'> print(list(num)) #切片操作[start:stop:step ] l5 = list(range(10)) print(l5) print(l5[::]) print(l5[0::]) print(l5[0:2:]) print(l5[0:2]) print(l5[::-1]) print(l5[1::2]) print(l5[::2]) print(l5[1:3]) #1-2
9. Python的列表的函数
-
list的多种创建方法
-
list的切片操作
-
list的zip函数和enumerate函数
-
list的基本的操作函数
-
l1 = list(range(10)) print(l1) print(l1[0]) # 列表操作包含以下函数: # 1、cmp(list1, list2):比较两个列表的元素---在Python3中取消了cmp函数,在Python2中可用的 # 2、len(list):列表元素个数 print(len(l1)) # 3、max(list):返回列表元素最大值 print(max(l1)) # 4、min(list):返回列表元素最小值 print(min(l1)) # 5、list(seq):将元组转换为列表 # 列表操作包含以下方法: # 1、list.append(obj):在列表末尾添加新的对象 l1.append("apple") print("result value is:",l1) # 2、list.count(obj):统计某个元素在列表中出现的次数 print("list count:",l1.count("apple")) # 3、list.extend(seq):在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) l1.extend([6,7,8,9]) print("change x value is:",l1) # 4、list.index(obj):从列表中找出某个值第一个匹配项的索引位置 print(l1.index("apple")) # 5、list.insert(index, obj):将对象插入列表 l1.insert(10,"pear") print(l1) # 6、list.pop(obj=list[-1]):移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 print(l1.pop()) print(l1.pop()) # 7、list.remove(obj):移除列表中某个值的第一个匹配项 l1.remove("apple") print(l1) # 8、list.reverse():反向列表中元素 l1.reverse() print(l1) print(l1[::-1]) # 9、list.sort([func]):对原列表进行排序 l1.sort(key=lambda x:len(str(x)),reverse=False) print(l1)
10. Python的元祖的操作
-
tuple
-
代码
-
#-*- coding: utf-8 -*- # @Time : 2019/11/10 14:54 # @Author : time # @Email : load # @File : 12.0tuple.py t1=(1,2,3,4,5,6) print(t1) print(type(t1)) #其他创建方式 t2=tuple([1,2,3,4]) print(t2) t3=tuple({1,2,3,4}) print(t3) t4=tuple({1:"apple",2:"pear",3:"banana",4:"orange"}) print(t4) t5=tuple({1:"apple",2:"pear",3:"banana",4:"orange"}.keys()) print(t5) t6=tuple({1:"apple",2:"pear",3:"banana",4:"orange"}.values()) print(t6) t7=tuple({1:"apple",2:"pear",3:"banana",4:"orange"}.items()) print(t7) #如果在一个tuple中有一个定义的list,请问list中的元素是否可以变更 t3= (1, 2, 3, 4, ["apple", "ok", 2]) print(t3) print(t3[0]) print(t3[1]) print(t3[2]) print(t3[3]) print(t3[4]) t3[4][0]="penapplepen" print(t3) #如果定义只有一个元素的tuple,如何定义? t4=(1,) print(type(t4)) #从tuple--->list解冻--->里面元素可变 #tuple可以进行多元素的赋值--------序列解包 a,b,c=1,2,3 print(a,b,c) (m,n,p)=1,2,3 v=(m,n,p) print(v)
11. Python的字典的操作
-
key-value
-
创建补充
fruit = {"apple": 1, "pear": 2, "banana": 3}
print(fruit)
print(type(fruit))
d1 = dict(zip(["Apple", "pear", "bababa"], [1, 2, 3]))
print(d1)
print(d1.keys())
print(d1.values())
print(d1.items())
d2 = dict(Apple=1, Pear=2, Bnanna=3)
print(d2)
#1-key是需要具备什么结构的才可以充当?答案:可Hash的
print(hash("apple"))
print(hash("pear"))
# print(hash(["pear"]))#TypeError: unhashable type: 'list'
print(hash(("1000")))
ssss_ = {"apple": 1, "banana": 2, ("ssss"): 3}#TypeError: unhashable type: 'list'
print(ssss_)
#2-key是不可以重复的部分,如果重复的key需要理解业务含义
pear_ = {"Apple": 1, "pear": 2, "banana": 3, "pear": 100}
print(pear_)
# del ssss_
# print(ssss_)
pear_.clear()
print(pear_)
- 函数的详解
# 六、字典内置函数&方法
d1 = dict(zip([1, 2, 3], ["apple", "pear", "banana"]))
print(d1)
# Python字典包含了以下内置函数:
# 1、cmp(dict1, dict2):比较两个字典元素。---在3中去掉了方法
# 2、len(dict):计算字典元素个数,即键的总数。
print(len(d1))
# 3、str(dict):输出字典可打印的字符串表示。
print(str(d1))
# 4、type(variable):返回输入的变量类型,如果变量是字典就返回字典类型。
# Python字典包含了以下内置方法:
# 1、radiansdict.clear():删除字典内所有元素
# 2、radiansdict.copy():返回一个字典的浅复制
# 3、radiansdict.fromkeys():创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
# 如:print "fromkeys",dict_2.fromkeys(dict_2,10)
# 4、radiansdict.get(key, default=None):返回指定键的值,如果值不在字典中返回default值
print(d1.get(1))
# 5、radiansdict.__contains__(key):如果键在字典dict里返回true,否则返回false
# 6、radiansdict.items():以列表返回可遍历的(键, 值) 元组数组
# 7、radiansdict.keys():以列表返回一个字典所有的键
# 8、radiansdict.setdefault(key, default=None):和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default
# 9、radiansdict.update(dict2):把字典dict2的键/值对更新到dict里
d1.update({"orange":234,"ooo":45})
print(d1)
# 10、radiansdict.values():以列表返回字典中的所有值
12. set集合
- 集合满足无序性、唯一性、确定性
set1 = {1, 2, 3, 5, 7, 10}
print(set1)
#集合的增加
set1.add("apple")
print(set1)
#集合的删除
set1.remove("apple")
print(set1)
#集合的删除
set1.discard(10)
print(set1)
#集合的更新
set1.update({9,8,7})
print(set1)
#集合运算
# 集合的交集
set3={1,2,3,6}
set2={9,8,7,6}
print(set2 & set3)
print(set2.intersection(set3))
# 集合的并集
print(set2 | set3)
print(set2.union(set3))
# 集合的补齐
print(set2 -set3)
print(set2.difference(set3))
13. 列表表达式
-
求解满足条件的列表
-
[表达式 for变量 in 可迭代的对象中 if 条件判断]
# 列表表达式 [表达式 for 变量 in 可迭代的对象中 if 条件判断]
# 目的:求解满足条件的列表
# x*x]
result = []
for x in range(10):
result.append(x * x)
print(result)
# 等价于
result1 = [x * x for x in range(10) if x != 0]
print(result1)
# 等价于
# map函数的用法,就是将函数应用在序列上面去
def add(x):
return x * x
r1 = map(add, range(10))
print(list(r1))
# 等价于map(_.split("")).map(x=>x*2)
r2 = list(map(lambda x: x * x, range(10)))
print(r2)
# 1.使用列表推到式实现嵌套列表的平铺(两个for循环)
vec = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(vec)
# 等价
result3 = []
for i in vec:
for j in i:
result3.append(j)
print(result3)
# 等价
result4 = [j for i in vec for j in i]
print(result4)
# 等价
# def re(*vec):
# for i in vec:
# result3.append(i)
# return result3
# print(list(map(re,vec)))
# 2.过滤不符合条件的元素
vec1 = [1, 2, 3, 4, -1, -2, -3, -10, 0]
result5 = []
for i in vec1:
if i > 0:
result5.append(i)
print(result5)
# 等价于
result6 = [x for x in vec1 if x > 0]
print(result6)
# 等价于
def sub(x):
if x > 0:
return x
else:
return -1
print(list(map(sub, vec1)))
# 3.列表推导中使用多个循环实现多序列元素任意的组合,并过滤元素
result7 = []
for i in range(10):
for j in range(10):
if i != j:
result7.append((i, j))
print(result7)
# 等价于
result8 = [(x, y) for x, y in zip(range(10), range(10))]
print(result8)
result9 = [(x, y) for x in range(10) for y in range(10) if x != y]
print(result9)
print(result9==result7)
#4.实现列表推到式实现矩阵转置
vec3=[[1,2,3],[4,5,6],[7,8,9]]
print(list(range(3))) # 012
print(list(range(0,3))) # 012
print(list(range(0,3,1))) # 012
result10=[[row[i] for row in vec3] for i in range(3)]
print(result10)
#zip
print(list(zip([1,2,3],[4,5,6],[7,8,9])))
print(list(map(list,zip([1,2,3],[4,5,6],[7,8,9]))))
##5.使用列表推导生成100以内的所有素数
#10-----1) 2---9/10 2)2---5(2/10) 3)2----sqrt(10)
sushu = [p for p in range(2, 101) if 0 not in [p % q for q in range(2, p)]]
print(sushu)
import numpy as np
sushu1 = [p for p in range(2, 101) if 0 not in [p % q for q in range(2, int(np.sqrt(p))+1)]]
print(sushu1)
from functools import reduce
def add(x,y):
return x+y
result10 =reduce(add, range(5))
print(result10)
seq1 = ['foo', 'x41', '?1', '***']
print(list(filter(lambda x:x.isalnum(),seq1)))
print(list(filter(lambda x:x!=0,[1,2,3,0,0,4,0,5])))
print(list(filter(None,[1,2,3,0,0,4,0,5])))
#If function is None, return the items that are true
list2=["apple","pear","ok","banananna"]
list2.sort(key=lambda x:len(str(x)),reverse=True)
print(list2)
14. 字典表达式/生成器表达式
- 生成器表达式
# 元祖表达式 (表达式 for 变量 in 可迭代的对象中 if 条件判断) 惰性求值
# x*x
re1 = (x * x for x in range(10))
print(re1.__next__())
print(re1.__next__())
print(re1.__next__())
print(list(re1))
print(list(re1))
- 字典表达式
# 字典表达式 {key:value for 变量 in 可迭代的对象中 if 条件判断}
A=["a","b","c","d"]
V=[1,2,3,4]
dict1 = {key: value for key, value in zip(A, V)}
print(dict1)
print(type(dict1))
from collections import OrderedDict
order = OrderedDict()
order["apple"]=100
order["banana"]=200
print(order)
print(ord("A"))
print(ord("a"))#ASCII
- 基本数据结构和表达式
15. 函数的结构
- 函数的参数和返回值
# -*- coding: utf-8 -*-
# @Time : 2019/11/10 16:59
# @Author : time
# @Email : load
# @File : 19.0pythonFunctions.py
# 函数:函数的参数+函数的返回值
# 1-没有参数没有返回值
def sayHello():
print("Hello"*5)
sayHello()
sayHello()
sayHello()
sayHello()
# 2-没有参数有返回值
def syaHi():
return "Hello "*5
syaHi()
syaHi()
syaHi()
# 3-有参数没有返回值
def addThreeNumber(a,b,c):
print(a+b+c)
# 4-有参数有返回值
def addThreeNumber1(a,b,c):
return a+b+c
X=60
def showNumber(X):
print("current number is:",X)
X=100
print("change number is:",X)
showNumber(X)
print("Final X value is:",X)
Y=100
def showNumber1():
global Y
print("current Y value is:",Y)
Y=200
print("change Y is:",Y)
showNumber1()
print("Final Y is:",Y)
if __name__ == '__main__':
addThreeNumber(1, 2, 3)
number_ = addThreeNumber1(1, 2, 3)
print(number_)
- 函数的参数
#默认参数
def SayHello(str="hhh",times=12):
print(str*times)
SayHello("Hello",10)
SayHello("Hello")
#关键字参数
def AddThreeNumber(a,b,c=10):
print(a+b+c)
AddThreeNumber(1,2,3)
AddThreeNumber(c=1,b=2,a=3)
AddThreeNumber(a=1,b=2)
#变长参数
def printFunctions(fparamters,*tuples1,**dict1):
print("paramberts",fparamters)
print("tuples1:",tuples1)
print("dict1:",dict1)
printFunctions(1,2,3,"apple","pear",name="Zhsngan",age=12)
vec=[[1,2,3],[4,5,6],[7,8,9]]
print(*vec)
print(list(zip([1,2,3],[4,5,6],[7,8,9])))
print(list(zip(*vec)))
vec1=[1,2,3]
print(*vec1)
def addThreeNumber(a,b,c):
print(a+b+c)
addThreeNumber(*vec1)
def demo1(*p):
print(p)
demo1(1,2,3)
demo1(1,2,3,34)
def demo2(**p):
for item in p.items():
print(item)
demo2(x=1,y=2,z=3) #key和value形式
- lambda表达式
# 语法:lambda 变量:表达式
# x*x
#lambda匿名函数---没有名字
g = lambda x: x * x
print(g(10))
x_x = (lambda x: x * x)(10)
print(x_x)
#map
m = list(map(str, range(10)))
print(m)
print(type(m))