luobo2ni 发表于 2018-8-9 09:13:13

【机器学习】Python 快速入门笔记

  Python 快速入门笔记
  Xu An   2018-3-7
  1、Python print
#在Python3.X中使用print()进行输出,而2.x中使用()会报错  
print("hello world")
  
print('I\'m apple')#如果全部使用单引号,则需要在前面加上转义字符\+引号
  
print('apple'+'pear')
  
print('apple'+str(4)) #将数字转换为字符串并打印
  
print(int("1")+2)#将字符串转换为整数类型
  2、pyhton数值运算
print(2**2)   #幂运算为**  
print(10%3)   #取余数为%
  
print(9//4)   #取整数为//
  3、自变量定义
a,b,c=1,2,3#一次定义多个变量  
print(a,b,c)
  4、while循环
condition=1  
while condition<10:
  
    print(condition)
  
    condition+=1
  5、for循环(相当于迭代器)
x=1  
y=2
  
z=3
  
if x<y<z:
  
    print(&quot;x is less than y&quot;)
  6、if-else语句
if x<y:  
    print(&quot;x<y&quot;)
  
else:
  
    print(&quot;x>y&quot;)
  7、if-elif-else
if x<y:  
    print(&quot;x<y&quot;)
  
elif x==y:
  
    print(&quot;&quot;)
  
else:
  
    print(&quot;x>y&quot;)
  8、函数定义
def add(a,b):   #在python中定义函数需要使用def()  
    c=a+b
  
    print(&quot;This is the result of the addtion:&quot;,c)
  
add(1,3)
  9、默认函数参数
def car(price,color='red',second_hand=True):  
#在函数参数后面加=“默认值”可以完成默认值的赋值
  
#bool类型中的参数需要大写True、Flase
  
#需要把默认参数放到变量的后面
  
    print('price',price,
  
      'color',color,
  
      'second_hand',second_hand,
  
      )
  
car(1000)
  10、变量类型
  '''
  (1)全局变量
  在模块内、所有函数外、class外的变量,可以被全局共享,也可以被外部文件共享
  全局变量使用时,需要使用global显式声明
  如果不将全局变量更新,一般不需要加global声明
  如果有重新赋值,又没有在函数内部使用global声明时,相当于在内部创建了一个同名的局部变量
  同名局部变量优先级高于未显式声明的全局变量
  '''
APPLE=10   #全局变量需要在函数外部定义  
def test10_01():
  
    global APPLE#在函数内部定义全局变量
  
    APPLE=20#在函数内声明的局部变量的优先级高于全局变量
  
    print(APPLE)
  
test10_01()
  '''
  (2)局部变量
  在函数内、class方法内(未加self修饰)
  生命周期在函数执行时,当函数执行完毕后局部变量消亡
  '''
def test10_02():  
    city='shijiazhuang'
  
    print(city)
  '''
  (3)静态变量(类变量)
  通过类名直接访问,也可以通过实例名直接访问,变量在类中、实例间全局共享
  '''
# class foo:  
#   all=0
  
#   def add(self):
  
#         foo.q+=1
  
# ins_1=foo() #实例化对象1
  
# ins_2=foo() #实例化对象2
  
# print(ins_1.all) #0
  
# print(ins_2.all) #0
  
# print(foo.all)   #0
  
# ins_1.add() #静态全局变量加1
  '''
  (4)实例变量
  对于模块来说,拥有自己的全局变量,可以供自己内部的类,函数使用
  对于类或者方法来说,有自己的局部变量,供自己内部使用
  对于类,有了静态变量,可以供内部和有继承关系的父子使用
  实例间各自的局部变量需要靠动态绑定多态实现
  '''
class foo_1:  
    all=0
  
    def __init__(self,name):
  
      self.name=name
  
    def add(self):
  
      foo.q+=1
  '''
  (5)总结
  私有变量:自己独享的变量,如函数和方法的局部变量,实例变量
  公有变量:需要在一定范围内共享,达到同步的目的,如模块内的代码共享的全局变量,类与子类之间共享的静态变量
  '''
  11、文件写入
text=&quot;This is my first text.\nThis is next line\n&quot; #使用\n表示换行,主要换行指令与C++一致  
print(text)
  
my_file=open('1.txt','w')
  
#open可以打开一个文件,open(‘文件路径’,‘形式’),形式w为可写形式,r为只读形式
  
my_file.write(text) #在文件中写入相应的语句
  
my_file.close()#切记在文件写入后要使用close方法关闭文件
  
print('Flie writing completed.')
  12、文字内容追加
my_file=open('1.txt','a') #方式a是append的缩写,表示文件的追加模式  
append_text=&quot;this is appened text&quot;
  
my_file.write(append_text)
  
my_file.close()
  # 13、读文件
my_file=open('1.txt','r') #r为读模式  
content=my_file.read()#读取文件内容需要使用read()方法
  
second_read=my_file.readline()
  
third_read=my_file.readline() #readline为逐行输出文字
  
all_read=my_file.readlines()#逐行读取后会将读取的元素按行放置在一个列表中
  
print(content,'second_read',second_read,'third_read',third_read,'all_read',all_read)
  14、类(class)
class Calculator: #类一般为大写  
    def __init__(self,name,price):#构造函数,在进行对象实例化时必须赋值,前面需要加上self
  
      self.name=name
  
      self.price=price
  
    name=&quot;Calculator&quot;
  
    price=10
  
    def add(self,x,y):
  
      print(self.name)#如果要在类内调用本身的方法,需要加上self.属性名或self.方法名
  
      result=x+y
  
      print(result)
  
    def minus(self,x,y):
  
      result=x-y
  
      print(result)
  
    def times(self,x,y):
  
      result=x*y
  
      print(result)
  
    def devide(self,x,y):
  
      result=x/y
  
      print(result)
  
newcalulator=Calculator('name',10)
  
print(newcalulator.name)
  15、input
a_input=input('Please give me a number:')   #input的功能为输入,其后面的括号为提示信息,input的返回值为输入的内容(是str类型),并赋值给对应的参数  
int_input=int(a_input)   #对字符串需要转换为int类型后进行判断
  
if int_input==1:
  
    print('your input is 1')
  
elif int_input==2:
  
    print('your input is 2')
  
else:
  
    print('your input number is other')
  16、元组 使用小括号或者不使用括号
a_tuple=(1,2,3,43)#元组可以用小括号的形式,也可以不加小括号  
another_tuple=1,12,43,23
  
for x in a_tuple:
  
    print(x)
  17、列表 使用中括号
a_list=  
for x in a_list:#将list的值使用for循环放到x中,之后打印出来
  
    print(x)
  
for index in range(len(a_list)):    #range()会生成一个迭代器,index为索引
  
    print(&quot;index=&quot;,index,'number in list=',a_list)
  
a=
  
a.append(0) #在列表后面追加一个元素
  
print(a)
  
a.insert(1,0) #insert(添加位置,数值)
  
a.remove(2) #remove(第一次出现的数值)
  
print(a)
  
a.index(1)#列表中第一次出现该数值的索引
  
a.sort(reverse=True) #默认为从小到大进行排序,加入reverse则进行从大到小进行排序
  
print(a)
  18、多维列表
a=  
multi_dim_a=[,,]
  
print(multi_dim_a)   #使用[][]进行索引
  19、字典 使用大括号
d={'apple':1,'pear':2,'orange':3} #冒号前面的为key,后面的为内容,字典的key唯一,如果不唯一则记住后面的元素,其不能是列表,以保证其唯一性要求  
print(d['apple']) #打印字典的值
  
del d['pear']#从字典中删除元素
  
d['b']=20      #加入元素到字典
  
print(d) #因为字典采用hash存储,所以字典是一个无序的容器
  20、import模块
#方法一:  
# import time #直接使用模块名进行后续操作
  
# print(time.localtime())
  
# 方法二:
  
# import time as t #如果模块名太长可以使用简称
  
#方法三:
  
# from time import localtime 只引入模块的某个功能
  
# print(localtime()) #如果使用本方法,可以不用写time.localtime,而直接写localtime()
  
#方法四:
  
from time import * #加*可以结束
  
print(localtime())
  21、引入自己的模块
# 确保自己的模块(同为.py文件)和本文件在同一个目录下,  
# import m1 #自己的模块名,其中定义了函数
  
# m1.function() 直接调用其函数即可,在macox中,其包目录在site-package中,如果将自建模块放入其中,则可以直接调用
  22、break&continue
a=True  
while a:
  
    b=input('Please enter something:')
  
    if b!='':
  
      print('enter is not blank')
  
      break
  23、错误处理
try:  
    File=open('12','r')
  
except Exception as e:
  
    print('there is no file named 12')
  
    response=input('do you want to creat a new file?(Y/N)')
  
    if response =='y'or'Y':#逻辑运算符 或or 且and 非not
  
      print('the file is created')
  
    else:
  
      pass #跳过
  24、zip(将两个列表合并为一个列表项) lambda map
a=  
b=
  
list(zip(a,b)) #zip返回为一个对象,如果想将其可视化,需要将其转化为list进行合并
  
for i,j in zip(a,b):
  
    print(i/2,j/2)    #生成一个迭代器进行输出
  
fun1=lambda x,y:print(x+y)
  
fun1(2,3)
  
def fun1(x,y):
  
    return(x+y)
  
                      #实现参数绑定
  
print(fun1,,)
  25、shallow copy &deep copy
import copy  
a=
  
b=a
  
print(id(a))#输出变量的唯一id,是赋值,b只是将a的地址进行了复制,而没有进行实际的变量值的拷贝
  
print(id(b))
  
c=copy.copy(a)
  
print('id of a:',id(a))
  
print('id of c:',id(c))      #浅拷贝,id不同,第一层空间地址不同,但是第二层空间(数组第二围)开始地址相同
  
d=copy.deepcopy(a)
  
print('id of a:',id(a))
  
print('id of c:',id(d))   #深拷贝,id不同,从第一层空间开始地址已经完全不同
  # 26、threading 线程
  # 27、multiprocessing 多核心
  # 28、tkinter GUI界面
  29、pickle 保存代码
import pickle  
# a_dic={'fruit':['apple','pear'],'vegetable':['tomato','cumcuber']}
  
# file =open('pickle_exm.pickle','wb')
  
# pickle.dump(a_dic,file)
  
# file.close()
  
# file=open('pickle_exm.pickle','rb')
  
# a_dic=pickle.load(file) #将之前保存的代码打开
  
# file.close()
  #或者自动关闭方案
with open('pickle_exm.pickle','rb') as file:  
    a_dic=pickle.load(file)
  30、使用set寻找不同
char_list=['a','b','c','c']  
print(set(char_list))   #使用set进行不同查找,输出结果为非重复序列,按hash排序
  
sentence='welcome to shijiazhuang'
  
print(set(sentence))#可以分辨句子中的不同字母,并以单个的形式呈现
  #31、正则表达式(待补充)
import re #引入正则表达式  
pattern1=&quot;cat&quot;
  
pattern2='dog'
  
string=&quot;dog runs to cat&quot;
  
print(pattern1 in string)#使用in来判断单词是否在目标语句中
  
#查找
  
print(re.search(pattern1,string))#使用正则表达式进行查找,查找到的内容会被以对象的形式返回
  
#匹配多种可能——使用[]
  
print(re.search(r&quot;rn&quot;,'dog runs to the cat'))
页: [1]
查看完整版本: 【机器学习】Python 快速入门笔记