一.外部模塊安裝
外部模塊就是在 import一些東西去python 腳本的時(shí)候會(huì)用到的.
比如Numpy屬于外部模塊罐农,在windows中丁存,可以在Numpy 安裝包的網(wǎng)站找到 numpy 的各種版本的安裝包.
二.文件讀取
- \n表示換行命令
text='This is my first test.\nThis is next line.\nThis is last line.'
print(text) #\n為換行命令,要注意斜杠方向
"""
This is my first test.
This is next line.
This is last line.
"""
2.用open打開一個(gè)文件台夺,open的第一個(gè)參數(shù)為文件名及路徑财松;第二個(gè)參數(shù)為形式梆掸,其中:"w"表示write,"r"表示read.
my_file=open('my file.txt','w') #打開文件
my_file.write(text) #文件中寫入之前定義的text
my_file.close() #關(guān)閉文件
3.給文件添加一行
append_text='\nThis is appended file.'
print(append_text)
my_file=open('my file.txt','a') #'a'表示append追加
my_file.write(append_text)
my_file.close()
4.讀取文件內(nèi)容
file=open('my file.txt','r')
content=file.read() #讀取文件全部內(nèi)容
print(content)
"""
This is my first test.
This is next line.
This is last line.
This is appended file.
"""
file=open('my file.txt','r')
content=file.readline() #讀取第一行
second_read_time=file.readline() #讀取第二行
print(content,second_read_time)
"""
This is my first test.
This is next line.
"""
file=open('my file.txt','r')
content=file.readlines() #讀取所有行扬卷,python_list形式
print(content)
"""
['This is my first test.\n', 'This is next line.\n', 'This is last line.\n', 'This is appended file.']
"""
三.class類
1.用class定義一個(gè)類.
class Calculator: #類的名稱首字母要大寫,注意冒號(hào)
name='Good calculator' #class的屬性
def add(self,x,y): #定義class的功能
print(self.name)
result=x+y
print(result)
def minus(self,x,y):
result=x-y
print(result)
def times(self,x,y):
print(x*y)
def divide(self,x,y):
print(x/y)
cal=Calculator() #這里運(yùn)行class時(shí)一定要加()
2.class類init功能
init(前后為雙下劃線)可以理解成初始化class的變量,可以在運(yùn)行時(shí)酸钦,給初試值賦值.
class Calculator:
def __init__(self,name,price,hight=12,width=15,weight=20): #給屬性設(shè)置默認(rèn)值
self.name=name
self.price=price
self.h=hight
self.wi=width
self.we=weight
c=Calculator('Bad calculator',10)
print(c.name,c.price,c.h,c.wi,c.we)
"""
Bad calculator 10 12 15 20
"""
四.input輸入
1.variable=input(): 表示運(yùn)行后怪得,可以在屏幕中輸入一個(gè)數(shù)字,該數(shù)字會(huì)賦值給自變量.
a_input=input('Please give a number:')
print('This input number is:',a_input)
"""
Please give a number:12 #input12
This input number is: 12
"""
2.input()應(yīng)用在if中钝鸽,若input不定義成整型汇恤,則if語句中的自變量a_input對應(yīng)的1和2應(yīng)寫成字符串形式.
a_input=int(input('Please give a number:')) #定義成int()整數(shù)型
if a_input==1:
print('This is a good one')
elif a_input==2:
print('See you next time')
else:
print('Good luck')
"""
Please give a number:1 #input1
This is a good one
"""
五.元組tuple 列表list
1.元組tuple用小括號(hào)或者無括號(hào)來表示,列表list用中括號(hào)來表示拔恰,它們都表示一連串有順序的數(shù)字因谎,它們的元素可以一個(gè)一個(gè)被迭代、輸出颜懊、運(yùn)用财岔、定位取值.
a_tuple=(12,3,5,15,6) #元組
another_tuple=2,4,6,7,8
a_list=[12,3,67,7,82] #列表
for content in a_list: #一個(gè)一個(gè)按順序輸出
print(content)
"""
12
3
67
7
82
"""
for index in range(len(a_tuple)): #len表示length,元組的長度
print('index=',index,'number in list=',a_tuple[index])
"""
index= 0 number in list= 12
index= 1 number in list= 3
index= 2 number in list= 5
index= 3 number in list= 15
index= 4 number in list= 6
"""
2.list添加
a=[1,2,3,4,2,3,1,1]
a.append(0) #給a的最后面添加一個(gè)0
a.insert(1,0) #在a的位置1處添加0
print(a)
#[1, 0, 2, 3, 4, 2, 3, 1, 1, 0]
注:列表位置從0開始
3.list移除
a=[1,0,2,3,4,2,3,1,1,0]
a.remove(2) #移除掉a中第一次出現(xiàn)的2
print(a)
#[1, 0, 3, 4, 2, 3, 1, 1, 0]
4.list索引
a=[1,0,3,4,2,3,1,1,0]
print(a[0]) #打印a中第0位的值
#1
print(a[-1]) #打印a中最后一位的值
#0
print(a[0:3]) #打印a中第0,1,2位即前三位的值
#[1,0,3]
print(a[5:]) #打印a中第五位及其之后的值
#[3,1,1,0]
print(a[-3:]) #打印a中倒數(shù)第三位及其之后的值
#[1,1,0]
print(a.index(2)) #列表中第一次出現(xiàn)2的索引
#4
print(a.count(1)) #列表中出現(xiàn)1的次數(shù)
#3
5.list排序
a=[1,0,3,4,2,3,1,1,0]
a.sort() #默認(rèn)對a從小到大排序
print(a)
#[0, 0, 1, 1, 1, 2, 3, 3, 4]
a.sort(reverse=True) #對a從大到小排序
print(a)
#[4, 3, 3, 2, 1, 1, 1, 0, 0]
6.多維列表
multi_dim_a=[[1,2,3],
[2,3,4],
[3,4,5]] #多維列表,三行三列
print(multi_dim_a[0][0]) #打印第0行第0個(gè)位置
#1
print(multi_dim_a[2][2]) #打印第2行第2個(gè)位置
#5
六.字典dictionary
字典沒有順序河爹;以大括號(hào)的形式表示匠璧;有key和value兩種元素,數(shù)字和字符串都可以當(dāng)做key和value咸这,字典的元素可以是一個(gè)列表夷恍、可以是一個(gè)function、還可以是字典媳维,形式多樣.
d= {'apple':[1,2,3],'pear':{1:3,3:'c'},'orange':3} #一個(gè)key對應(yīng)一個(gè)value
d2={1:'a','c':'b'} #key和value可以是字符串或數(shù)字
print(d['apple']) #打印d中的apple
#[1,2,3]
print(d['pear'][3]) #打印d中的pear中的3
#c
del d['pear'] #刪除d中的pear
print(d)
#{'apple': [1, 2, 3], 'orange': 3}
d['b']=20 #給d中加入b
print(d)
#{'apple': [1, 2, 3], 'orange': 3, 'b': 20}
七.import 載入模塊
方法一:
import time #加載time模塊酿雪,python自帶
print(time.localtime()) #print出當(dāng)?shù)貢r(shí)間
"""
time.struct_time(tm_year=2020, tm_mon=6, tm_mday=24, tm_hour=17, tm_min=18, tm_sec=31, tm_wday=2, tm_yday=176, tm_isdst=0)
"""
方法二:
import time as t #把time簡稱為t
print(t.localtime)
"""
time.struct_time(tm_year=2020, tm_mon=6, tm_mday=24, tm_hour=17, tm_min=18, tm_sec=31, tm_wday=2, tm_yday=176, tm_isdst=0)
"""
方法三:
from time import time,localtime #只要time和localtime兩個(gè)功能
print(localtime())
print(time())
"""
time.struct_time(tm_year=2020, tm_mon=6, tm_mday=24, tm_hour=17, tm_min=18, tm_sec=31, tm_wday=2, tm_yday=176, tm_isdst=0)
1592990311.6439924
"""
方法四:
from time import* #import所有功能
print(time())
"""
1592990311.6439924
"""
八.continue和break
1.跳出循環(huán):當(dāng)a=False時(shí),會(huì)執(zhí)行接下來的語句后再跳出這個(gè)循環(huán).
a=True
while a:
b=input('type something')
if b=='1':
a=False
else:
pass
print('still in while')
print('finish run')
"""
type something2
still in while
type something1
still in while #會(huì)執(zhí)行下面的語句再跳出
finish run
"""
2.break:當(dāng)符合跳出條件時(shí)侄刽,會(huì)直接結(jié)束循環(huán).
while True:
b=input('type something')
if b=='1':
break
else:
pass
print('still in while')
print('finish run')
"""
type something2
still in while
type something1
finish run #直接跳出循環(huán)
"""
3.continue:當(dāng)滿足條件時(shí)指黎,不會(huì)執(zhí)行 else 后面的代碼,而會(huì)直接進(jìn)入下一次循環(huán).
while True:
b=input('type something')
if b=='1':
continue
else:
pass
print('still in while')
print('finish run')
"""
type something2
still in while
type something1 #不執(zhí)行else后的代碼州丹,直接進(jìn)入下一次循環(huán)
type something
"""
九.錯(cuò)誤處理try
1.輸出錯(cuò)誤
try:
file=open('eeee','r') #會(huì)報(bào)錯(cuò)的代碼
except Exception as e: #接收錯(cuò)誤醋安,儲(chǔ)存在e中
print(e)
"""
[Errno 2] No such file or directory: 'eeee'
"""
2.處理錯(cuò)誤
try:
file = open('eeee', 'r+w')
except Exception as e:
print('there is no file named as eeee') #首先報(bào)錯(cuò)
response = input('do you want to create a new file') #決定是否輸入y
if response == 'y':
file = open('eeee', 'w') #輸入y后杂彭,會(huì)新建一個(gè)文件
else:
pass
else:
file.write('ssss') #再次運(yùn)行,文件中會(huì)寫入ssss
file.close()
"""
there is no file named as eeee
do you want to create a new filey
"""
十.zip lambda map
1.zip函數(shù)接受任意多個(gè)(包括0個(gè)和1個(gè))序列作為參數(shù)吓揪,合并后返回一個(gè)tuple列表
a=[1,2,3]
b=[4,5,6]
ab=zip(a,b) #把a(bǔ)和b豎向合并
print(list(ab)) #加list可視化這個(gè)功能
"""
[(1, 4), (2, 5), (3, 6)]
"""
for i,j in zip(a,b):
print(i/2,j*2) #zip中的運(yùn)算
"""
0.5 8
1.0 10
1.5 12
"""
print(list(zip(a,a,b))) #可以zip更多元素
"""
[(1, 1, 4), (2, 2, 5), (3, 3, 6)]
"""
2.lambda定義一個(gè)簡單函數(shù)亲怠,有簡化代碼的功能.
fun2=lambda x,y:x+y #x,y為自變量,x+y為具體運(yùn)算
print(fun2(2,3))
#5
3.map把函數(shù)和參數(shù)綁定在一起.
def fun1(x,y):
return(x+y)
print(list(map(fun1,[1],[2])))
"""
[3]
"""
print(list(map(fun1,[1,3],[2,5])))
"""
[3,8]
"""
十一.淺復(fù)制&深復(fù)制 copy&deepcopy
1.賦值
import copy #加載copy模塊
a=[1,2,3]
b=a #賦值
print(id(a)) #a在內(nèi)存中的地址
#1932900954560
print(id(a)==id(b)) #賦值后柠辞,兩者id相同
#True
b[0]=11 #改變b的第一個(gè)值赁炎,a也會(huì)改變
print(a)
#[11, 2, 3]
2.淺拷貝
a=[1,2,3]
c=copy.copy(a) #淺拷貝,只拷貝了a的外圍對象本身
print(id(a)==id(c))
#False
c[1]=222222 #改變c的第二個(gè)值钾腺,a不會(huì)被改變
print(a,c)
#[1, 2, 3] [1, 222222, 3]
a=[1,2,[3,4]] #第三個(gè)值為列表,是內(nèi)部元素
d=copy.copy(a) #只用淺拷貝只是對內(nèi)部元素的引用
print(id(a)==id(d))
#False
print(id(a[2])==id(d[2]))
#True
a[0]=11 #改變a中的第一個(gè)值讥裤,d不會(huì)改變
print(d)
#[1, 2, [3, 4]]
a[2][0]=333 #改變a的內(nèi)部元素的一個(gè)值放棒,d也會(huì)改變
print(d)
#[1, 2, [333, 4]]
5.深拷貝
a=[1,2,[3,4]]
e=copy.deepcopy(a) #深拷貝,對外圍和內(nèi)部對象都進(jìn)行了拷貝
a[2][0]=33 #改變a中內(nèi)部元素列表第一個(gè)的值己英,e不會(huì)改變
print(e)
#[1, 2, [3, 4]]
print(id(e[2])==id(a[2]))
#False
十二.pickle 保存數(shù)據(jù)
pickle 是一個(gè)壓縮/保存/提取文件的模塊间螟,pickle可以保存字典、列表和變量等.
1.pickle保存
import pickle
a_dict={'da':111,2:[23,1,4],'23':{1:2,'d':'sad'}}
file=open('pickle_example.pickle','wb')
pickle.dump(a_dict,file)
file.close()
2.pickle提取
with open('pickle_example.pickle','rb') as file: #會(huì)自動(dòng)關(guān)閉文件
a_dict1=pickle.load(file)
print(a_dict1)
十三.set找不同
1.set基本
char_list=['a','b','c','c','d','d','d']
print(set(char_list)) #找list中的不同元素
#{'d', 'c', 'b', 'a'}
sentence='Welcome Back to This Tutorial'
print(set(sentence))
#{'e', 'k', 'T', 's', 'o', 'W', 'h', 'B', ' ', 'r', 'm', 'i', 'u', 't', 'a', 'c', 'l'}
2.添加元素add
unique_char=set(char_list)
unique_char.add('x') #添加元素损肛,只能單獨(dú)加一個(gè)
print(unique_char)
#{'b','a','x','c','d’}
3.清除元素:清除一個(gè)元素可以用 remove 或者 discard厢破,remove清除不存在元素時(shí)會(huì)報(bào)錯(cuò),discard清除不存在元素時(shí)會(huì)繼續(xù)返回原有數(shù)據(jù)治拿;而清除全部可以用 clear.
unique_char.remove('x') #清除元素x
print(unique_char)
#{'b', 'a', 'c', 'd'}
unique_char.discard('d') #清除元素d
print(unique_char)
#{'b', 'a', 'c'}
unique_char.clear() #清除全部元素
4.篩選操作
set1=unique_char
set2={'a','e','i'}
print(set1.difference(set2)) #set1與set2不同的部分
#{'x', 'b', 'c', 'd'}
print(set1.intersection(set2)) #set1與set2相同的部分
#{'a'}