一筑悴、變量及數(shù)據(jù)類型
1.1魏宽、變量
-
變量的賦值操作
# 變量賦值
a = 100 # 賦值100給變量a
# 多變量同時賦值
a=b=c=1
e,f,g=1,2,'abc'
print(a,b,c,e,f,g)
# 動態(tài)變量
# 變量的值是可更改的呆馁,可隨時指向任意值
var=10
print(var)
var=20
print(var)
輸出結(jié)果:
1 1 1 1 2 abc
10
20
1.2數(shù)據(jù)類型(結(jié)構(gòu))
數(shù)據(jù)結(jié)構(gòu):通過某種方式組織在一起的數(shù)據(jù)元素的集合梗摇。這些數(shù)據(jù)元素可以說數(shù)字或者字符,甚至可以是其他數(shù)據(jù)結(jié)構(gòu)几缭。
在python中河泳,python的標(biāo)準(zhǔn)數(shù)據(jù)類型有numbers數(shù)字,string字符串年栓,list列表拆挥,tuple元祖,dict字典某抓,bool布爾型纸兔。
其中在python中黄锤,列表、元組食拜、字符串、也是python的內(nèi)建序列副编,在python中负甸,序列也是最基本的數(shù)據(jù)結(jié)構(gòu)。
-
numbers數(shù)字
numbers數(shù)字分為:int整型痹届,long長整型呻待,float浮點型,complex復(fù)數(shù)队腐。此處只舉例int蚕捉、float。
#int整型
a=10
#float浮點型
b=10.0
print(type(a),type(b)) #輸出a柴淘、b的數(shù)據(jù)類型
#函數(shù)print()迫淹,用于輸出/打印內(nèi)容
#函數(shù)type(),用于查看數(shù)據(jù)類型
輸出結(jié)果:
<class 'int'> <class 'float'>
-
string字符串
String字符串由數(shù)字为严、字母敛熬、下劃線組成的一串字符,用于表示文本的數(shù)據(jù)類型第股∮γ瘢可以用單引號,雙引號夕吻,三引號表示诲锹,用單引號和雙引號是一樣的,三引號可表示多行字符串涉馅。
st1='abc'
print(st1,type(st1))
st2="abc"
print(st2)
st3='''你好
大家好'''
print(st3)
輸出結(jié)果:
abc <class 'str'>
abc
你好
大家好
-
list列表
list列表归园,用[]標(biāo)識,是可變的有序?qū)ο笾煽蟆ist支持字符蔓倍,數(shù)字,字符串以包含列表(即嵌套)盐捷。
lst=[1,2,3,4,5,[1,2,3],'abc','efg']
print(lst,type(lst))
輸出結(jié)果:
[1,2,3,4,5,[1,2,3],'abc','efg'] <class 'list'>
-
tuple元祖
Tuple元祖偶翅,用()標(biāo)識,是不可變的有序?qū)ο蟮锒伞2荒芏钨x值聚谁,可以理解成不可變的列表(只讀列表)。
a=(1,2,3,'hello')
print(a,type(a))
輸出結(jié)果:
(1,2,3,'hello') <class 'tuple'>
-
dict字典
Dict字典滞诺,用{}標(biāo)識形导,是無序?qū)ο蠡诽邸S伤饕?key)和它對應(yīng)的值value組成,key-value是成對出現(xiàn)的朵耕。
dic={'a':1,'b':2,'c':3}
print(dic,type(dic))
輸出結(jié)果:
{'a':1,'b':2,'c':3} <class 'dict'>
-
bool布爾型
做bool布爾型的時候炫隶,輸出結(jié)果為True,F(xiàn)alse阎曹,是用于做判斷的伪阶。
a=True
print(a,type(a))
print(True == 1)
#表示True是否等于1
print(False == 0)
#表示False是否等于0
print(True * 10)
# 【注意】True實際值是1,F(xiàn)alse實際值是0
輸出結(jié)果:
True <class 'bool'>
True
True
10
1.3數(shù)據(jù)類型的轉(zhuǎn)換
int处嫌,float栅贴,str三者之間的轉(zhuǎn)換。分別用函數(shù)int(x),float(x),str(x)熏迹,對變量進行轉(zhuǎn)換檐薯。
# 整型轉(zhuǎn)為浮點型
a=12
b=float(a)
print(a,type(a))
print(b,type(b))
print('---------------------------')
# a是整型,通過函數(shù)float()將a轉(zhuǎn)換為浮點型
# 浮點型轉(zhuǎn)為整型
a=12.8
b=int(a)
print(a,type(a))
print(b,type(b))
#a是浮點型注暗,通過函數(shù)int()將a轉(zhuǎn)換為整型
#注意:用int()將浮點型轉(zhuǎn)為整型坛缕,是不會進行四舍五入的,也就是輸出結(jié)果是12捆昏,而非13
#若要四舍五入就使用函數(shù)round()
c=round(a)
print(c,type(c))
輸出結(jié)果:
12 <class 'int'>
12.0 <class 'float'>
---------------------------
12.8 <class 'float'>
12 <class 'int'>
13 <class 'int'>
若變量要轉(zhuǎn)換為字符串也是一樣的使用方法祷膳。
1.4運算符
-
算數(shù)運算符
# 加減乘除
a,b,c=1,2,3
print(a+b)
print(a-b)
print(a*b)
print(a/b)
# 取模,即系返回除數(shù)的余數(shù)
a,b=21,10
print(a%b)
# 取冪
a, b, = 2, 3
c = a**b # 冪
print(c)
# 也就是求a的b次方
# 取整除數(shù)
a, b = 10, 4
c = a//b
print(c)
# 取整除數(shù)屡立,也就是求10/4的整除數(shù)
輸出結(jié)果:
3
-1
2
0.5
1
8
2
-
比較運算符
a, b = 21, 10
print(a == b) # 等于
print(a != b) # 不等于
print(a > b) # 大于
print(a < b) # 小于
print(a >= 21) # 大于等于
print(a <= 2) # 小于等于
-
邏輯運算符
and直晨、or、not
print(True and False) # and:且
print(True or False) # or:或
print(not True) # not:非
# 布爾型的本質(zhì):True的值等于1膨俐,F(xiàn)alse的值等于0
print(True>0)
輸出結(jié)果:
False
True
False
True
【注意】將值轉(zhuǎn)換為布爾型時勇皇,只有以下這幾種情況布爾返回False,其余均返回True——
print(bool(0),bool(3),bool(-1),bool([1,2,3]),bool(0))
# 以上情況bool()返回False:0, 0.0, None焚刺,'', [] , {}
輸出結(jié)果:
False True True True False
-
成員運算符
# in和not in
lst = [1,2,3,4,5,6]
a,b = 1,10
print(a in lst)
#判斷a是否在lst 序列中敛摘,若為真返回True
print(b not in lst)
#判斷b是否不在lst序列中,若為真返回True
輸出結(jié)果:
True
True
1.5注釋#
注釋是用來說明代碼乳愉。程序運行的時候兄淫,Python解釋器會直接忽略掉注釋,即系有沒有注釋不影響程序的執(zhí)行結(jié)果蔓姚,但是影響到別人能不能看懂你的代碼捕虽。但“#”不只代表注釋,還代表某些文件的特殊格式,寫在腳本開頭坡脐,因此要注意——注釋只在腳本中起作用泄私。
二、序列及其通用操作
序列分類:可變序列l(wèi)ist,不可變序列tuple晌端、str捅暴。在python中,內(nèi)建了6中序列:列表咧纠、元組蓬痒、字符串、unicode字符串漆羔、buffer對象梧奢、xrange對象。
2.1序列的通用操作
-
序列通用功能
# 序列通用功能
print('a' in 'abc') # in/not in :判斷是否存在
print('我很帥' + "沒錯") # 文本連接
print('handsome '*4) # 文本復(fù)制
輸出結(jié)果:
True
我很帥沒錯
handsome handsome handsome handsome
-
序列基本的內(nèi)置函數(shù)
# 序列基本的內(nèi)置全局函數(shù)
lst=list(range(5))
tup=(33,56,89,100)
st='abcdef'
print(lst,tup,st)
# 求長度的函數(shù)len()
print(len(lst),len(tup),len(st))
# 求最大值和最小值的函數(shù)钧椰,max(),min()
print(max(lst),max(tup),max(st))
print(min(lst),min(tup),min(st))
#求和的函數(shù)sum()
print(sum(lst),sum(tup)) # 字符串str沒有求和的功能
#求索引的位置用方法.index()
print(lst.index(2)) #求lst序列中值為2的索引
print(tup.index(33)) #求tup序列中值為33的索引
print(st.index('d'))
print('-----------')
#求計數(shù)的方法.count()
lst=[1,2,3,3,3,3]
tup=(33,33,33,44,6)
st='aabbeeee'
print(lst.count(3)) # 計算lst序列中的3有幾個
print(tup.count(33))
print(st.count('e'))
輸出結(jié)果:
[0, 1, 2, 3, 4] (33, 56, 89, 100) abcdef
5 4 6
4 100 f
0 33 a
10 278
2
0
3
-----------
4
3
4
2.2可變序列:list列表常用操作
-
list列表的特征及創(chuàng)建
# 創(chuàng)建列表
lst1 = [1,2,3,'a','b','c',[1,2,3]]
print(lst1)
# 列表原位改變
lst5 = [100,101,102]
lst5[0] = 10
print(lst5)
#lst5的索引為0的值原本為100,后面重新賦值給索引為0的位置符欠,變?yōu)榱?0
#也是因為list是有序可變對象嫡霞,所以list的原位改變
# 列表的索引訪問元素
lst2 = [143,56,894,67,43]
print(lst2[0],lst2[4],lst2[-1])
# 正因為list列表是有序的對象,順序不能變希柿,因此通過索引來定位列表的元素
輸出結(jié)果:
[1, 2, 3, 'a', 'b', 'c', [1, 2, 3]]
[10, 101, 102]
143 43 43
-
list列表的下標(biāo)索引诊沪、切片、步長
# 下標(biāo)索引
lst=[1,2,3,4,5,6,7,8,9]
print(lst[0],lst[5],lst[8])
# 表示分別指向索引為0曾撤、索引為5端姚、索引為8的值
print(lst[-1],lst[-2])
print('--------------------------')
# 索引為-1代表列表的最后一個值,-2代表列表倒數(shù)第二個值,帶符號的以此類推
# lst此列表最大索引為8挤悉,不能定位超過最大索引
# 切片
lst=[1,2,3,4,5,6,7,8,9]
print(lst[0:3])
#因為左閉右開區(qū)間渐裸,索引表示索引0-2的值
print(lst[:5])
#左邊無索引數(shù),表示指向從索引0開始到索引4的值
print(lst[2:])
#右邊無索引數(shù)装悲,表示指向從索引2開始到最后一個索引的值
print(lst[5:-1])
#表示指向從索引5的值到倒數(shù)第二個值的區(qū)間
# 步長
lst = [1,2,3,4,5,6,7,8,9,0]
print(lst[0:5:2]) # List[i:j:n]代表:索引i - 索引j昏鹃,以n為步長
print(lst[::2]) # 按照2為步長,從第一個值開始截取lst數(shù)據(jù)
print(lst[1::2]) # 按照2為步長诀诊,從第二個值開始截取lst數(shù)據(jù)
輸出結(jié)果:
1 6 9
9 8
--------------------------
[1, 2, 3]
[1, 2, 3, 4, 5]
[3, 4, 5, 6, 7, 8, 9]
[6, 7, 8]
[1, 3, 5]
[1, 3, 5, 7, 9]
[2, 4, 6, 8, 0]
-
list列表添加元素
方法1:鏈接法給list列表添加元素洞渤,鏈接符號是“+”,并且鏈接的對象必須類型一致
lst1=[1,2,3,4,5]
lst2=['abc',1,3,5]
print(lst1+lst2)
輸出結(jié)果:
[1,2,3,4,5,'abc',1,3,5]
- 方法2:方法.append()給list列表尾部添加元素属瓣,將添加的對象作為一個整體對象添加到原列表list中载迄,所以是會改變了原列表list的
lst1=[2,4,6,8,0]
lst1.append(['a','b','c'])
print(lst1)
輸出結(jié)果:
[2, 4, 6, 8, 0, ['a', 'b', 'c']]
- 方法3:方法.extend()給list列表尾部添加元素,是將添加的對象中的每一個元素抡蛙,一個個添加在原始列表中护昧,所以同樣會改變原列表list的
lst1=[2,4,6,8,0]
lst1.extend(['a','b','c'])
print(lst1)
輸出結(jié)果:
[2, 4, 6, 8, 0, 'a', 'b', 'c']
-
list列表插入元素
# 列表插入元素,用方法.insert(索引粗截,值)
# 元素會被插入到指定索引的位置捏卓,原本位置的值依次后退
lst=['a','n','c']
lst.insert(1,100) # 在索引為1的地方插入值為100
print(lst)
輸出結(jié)果:
['a', 100, 'n', 'c']
-
list列表刪除元素
方法1:方法.remove(值),移除列表中的某個值
lst=[22,43,123,100]
lst.remove(100)
#將列表中的值100移除
print(lst)
輸出結(jié)果:
[22, 43, 123]
- 方法2:方法.pop(索引),移除列表中某個索引對應(yīng)的值
lst=[1,2,3,4,5]
lst.pop(1) # 將索引為1的值移除
print(lst)
輸出結(jié)果:
[1, 3, 4, 5]
- 方法3:方法.clear()怠晴,可清除列表的所有值
lst=[1,2,3,4,5,6,7,89]
lst.clear()
print(lst)
輸出結(jié)果:
[] #所有值都清除了遥金,所以返回為空列表
- 方法4:用del語句,刪除列表的某個值或某個范圍的值蒜田,或整個列表
lst=['a','b','c','d','f','g','h','i']
del lst[0] # 刪除索引為0的值
print(lst)
del lst[0:4] # 刪除索引為0-3的值
print(lst)
del lst #刪除整個列表
#print(lst) # 因為整個刪除了整個列表list所以不能返回
#返回就會報錯:NameError: name 'lst' is not defined
輸出結(jié)果:
['b', 'c', 'd', 'f', 'g', 'h', 'i']
['g', 'h', 'i']
-
list列表復(fù)制
假如需要對列表進行某種操作稿械,如添加或刪除元素,或其他操作冲粤,但希望原始列表保持不變美莫,可以通過復(fù)制一個列表,對副本操作而保持原始列表不變梯捕。
- 方法1:使用[:]復(fù)制一個列表
lst1=list('abcde')
print('我是原始列表',lst1)
# 使用[:]復(fù)制一個列表
# 在原始列表名稱后添加[:]厢呵,將其賦給要給新變量即可
lst2=lst1[:]
print('我是復(fù)制的列表副本',lst2)
lst2[0]=100
print(lst2)
print('原始列表不變:',lst1)
輸出結(jié)果:
lst1=list('abcde')
print('我是原始列表',lst1)
# 使用[:]復(fù)制一個列表
# 在原始列表名稱后添加[:],將其賦給要給新變量即可
lst2=lst1[:]
print('我是復(fù)制的列表副本',lst2)
lst2[0]=100
print(lst2)
print('原始列表不變:',lst1)
- 方法2:用方法.copy()傀顾,復(fù)制列表
lst1=[1,2,3,4,5]
lst2=lst1
lst1[4]=100 # 原位改變lst1索引為4的值襟铭,改為100
print(lst1,lst2) # 這時候lst2也會受影響改變,因為lst2=lst1
# 這時候若使用方法.copy()就可以杜絕以上情況
lst1=[1,2,3,4,5]
lst2=lst1.copy() # lst2就等于lst1的復(fù)制
lst1[4]=100
print(lst1,lst2)
輸出結(jié)果:
[1, 2, 3, 4, 100] [1, 2, 3, 4, 100]
[1, 2, 3, 4, 100] [1, 2, 3, 4, 5]
-
list列表元素排序
方法1:方法.sort()排序短曾,默認(rèn)升序排列
lst=[33,44,1,56,123,0,546]
lst.sort() # 默認(rèn)升序排列
print(lst)
lst.sort(reverse=True) # 參數(shù)reverse=True 按照降序排列
print(lst)
輸出結(jié)果:
[0, 1, 33, 44, 56, 123, 546]
[546, 123, 56, 44, 33, 1, 0]
- 方法2:用函數(shù)sorted()排序寒砖,默認(rèn)升序排列,且不改變原列表嫉拐,是復(fù)制一個原列表作為新列表進行排序
lst=[44,67,2,4,1,98,156,0]
lst2=sorted(lst)
print(lst) # 沒有改變原序列
print(lst2)
lst3=[333,42,6,11,0]
lst4=sorted(lst3,reverse=True) # 參數(shù)reverse=True 按照降序排列
print(lst3,lst4)
輸出結(jié)果:
[44, 67, 2, 4, 1, 98, 156, 0]
[0, 1, 2, 4, 44, 67, 98, 156]
[333, 42, 6, 11, 0] [333, 42, 11, 6, 0]
-
list列表與生成器range()
range()是生成器哩都,指向一個范圍。range()的數(shù)據(jù)類型是一個視圖婉徘,雖然生成的是一個視圖不是列表漠嵌,但是有可以做索引、切片盖呼、步長献雅。range()生成器用list()函數(shù)將指向的范圍變?yōu)榱斜韑ist
range()的切片、步長與list的切片塌计、步長有區(qū)別:
list的切片表示lst[0:3]挺身、步長表示lst[0:6:2]
range的切片表示range(0,3)、步長表示range(0,10,2)
b=range(5)
print(range(5),type(range(5)))
print(range(5))
#代表指向了0,1,2,3,4這幾個值
print(range(2,5))
#代表指向了2,3,4這幾個值
print(range(0,10,2))
#代表指向了0,2,4,6,8這幾個值锌仅,最后的2代表步長
a=list(range(10))
#用函數(shù)list()將生成器指向的0-9范圍變?yōu)榱斜韑ist
print(a,type(a))
輸出結(jié)果:
range(0, 5) <class 'range'>
range(0, 5)
range(2, 5)
range(0, 10, 2)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class 'list'>
2.3不可變序列:tuple元祖常用操作
-
tuple元祖的特征及創(chuàng)建
# 創(chuàng)建元祖
tup1=(1,2,3,4)
print(tup1,type(tup1))
tup2=(1,2,3,('a','b'),10)
print(tup2,type(tup2))
tup3=(1,2,3,['a','b'],(22,45))
print(tup3,type(tup3))
print('-----------------------')
# tuple元祖可以不加括號(了解就好章钾,一般不建議使用此寫法)
tup3 = "a", "b", "c", "d"
print(tup3)
print('-----------------------')
# tuple元組中只包含一個元素時,需要在元素后面添加逗號
tup4 = (50,)
print(tup4)
輸出結(jié)果:
(1, 2, 3, 4) <class 'tuple'>
(1, 2, 3, ('a', 'b'), 10) <class 'tuple'>
(1, 2, 3, ['a', 'b'], (22, 45)) <class 'tuple'>
-----------------------
('a', 'b', 'c', 'd')
-----------------------
(50,)
-
tuple元祖的下標(biāo)索引热芹、切片贱傀、步長
tuple元祖是有序的不可變序列,所以下標(biāo)索引伊脓、切片独柑、步長的使用與list一樣。但是因為是不可變序列题涨,所以tuple元祖是不可以做原位改變元素的,也不能添加元素剖淀、插入元素、刪除元素纤房、對元素進行排序纵隔。
tup=(2,31,45,90,100,23,56,'abc')
print(tup)
print(tup[1]) #定位索引為1的值
print(tup[0:4]) # 定位索引為0-3的值
print(tup[::2]) # 定位從頭到尾的索引的值且步長為2
輸出結(jié)果:
(2, 31, 45, 90, 100, 23, 56, 'abc')
31
(2, 31, 45, 90)
(2, 45, 100, 56)
-
刪除tuple元祖
因為tuple元祖是不可變序列,所以不可以單獨刪除內(nèi)部元素炮姨,但是可以用def語句刪除整個元祖捌刮。
tup1 = (1,2,3,4,5)
print(tup1)
del tup1
#print(tup1) #刪除整個元祖了,所以返回時會報錯的
輸出結(jié)果:
(1, 2, 3, 4, 5)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-60-8a01d172e139> in <module>()
2 print(tup1)
3 del tup1
----> 4 print(tup1)
NameError: name 'tup1' is not defined
2.4不可變序列:str字符串常用操作
字符串string舒岸,有序的不可變對象绅作。字符串是Python中最常用的數(shù)據(jù)類型。我們可以使用引號('或")來創(chuàng)建字符串蛾派,字符串也是序列——文本序列俄认。
補充:
判斷字符串是否含有空格:.isspace()
判斷字符串是否含有數(shù)字:.isdigit()
-
str字符串的特征及創(chuàng)建
# 字符串創(chuàng)建
str1 = "abc"
str2 = 'abc'
str3 = 'my name is "fatbird"'
# 雙引號單引號無區(qū)別,但文本中有引號的時候要相互交替使用
# 需要多行字符串時候用三引號 ''' ''',""" """
str4 = '''hello! how are you?
I`m fine, thank you.'''
輸出結(jié)果:
abc
abc
my name is "fatbird"
hello! how are you?
I`m fine, thank you.
-
str字符串的轉(zhuǎn)義字符\
# 換行符號 ‘\n'
print('尊敬的女士:\n 你好碍脏!')
print('\'', '\"')
# \',\" :分別輸出單引號梭依,雙引號
print('hello\nhow do you do?')
# \n:空行
print('\\')
# 輸出\稍算,所以文件路徑用“/”或者“\\
輸出結(jié)果:
尊敬的女士:
你好典尾!
' "
hello
how do you do?
\
-
str字符串的小標(biāo)索引、切片糊探、步長
str字符串的的索引钾埂、切片和步長的使用與list的使用類似。
# 創(chuàng)建字符串
s = 'abcdefghijklmn'
print(s,type(s))
print(s[0])
print(s[1:3])
print(s[::2])
輸出結(jié)果:
abcdefghijklmn <class 'str'>
a
bc
acegikm
-
修改str字符串元素
# str.replace(old,new,count):修改字符串
# old → 原字符串中要替換的字符串
# new → 新的字符串
# count → 更換幾個
st = "i`m handsome!"
st2 = st.replace('handsome','ugly')
print(st)
print(st2)
# 'handsome'換為'ugly'
st = 'hahaha'
st2 = st.replace('ha','he',2)
print(st2)
# 'ha'換為'he',而且換2個
輸出結(jié)果:
i`m handsome!
i`m ugly!
heheha
-
拆分str字符串
# 拆分字符串
# str.split(obj):拆分字符串科平,生成列表
st = "poi01,116.446238,39.940166"
print(st)
print(type(st))
lst = st.split(',') # 將字符串按逗號拆分
print(lst)
print(type(lst))
輸出結(jié)果:
poi01,116.446238,39.940166
<class 'str'>
['poi01', '116.446238', '39.940166']
<class 'list'>
-
連接str字符串
# 連接str字符串
# str.join():連接字符串褥紫,對象為字符串序列
lst = ['poi01', '116.446238', '39.940166']
print(lst,type(lst))
m = '-'
st = m.join(lst) # 用m將lst的元素連接起來
print(st,type(st))
輸出結(jié)果:
['poi01', '116.446238', '39.940166'] <class 'list'>
poi01-116.446238-39.940166 <class 'str'>
-
判斷str字符串的開頭/結(jié)尾
# 判斷字符串的開頭/結(jié)尾
st = 'abcdefg'
print(st.startswith('a'), st.endswith('f'))
# str.startswith(“str”) 判斷是否以“str”開頭;str.endswith (“str”) 判斷是否以“str”結(jié)尾
輸出結(jié)果:
True False
-
str字符串字母大小寫互換
# 字符串字母大小寫互換
st = 'aBDEAjc kLM'
print(st.upper()) # 全部大寫
print(st.lower()) # 全部小寫
print(st.swapcase()) # 大小寫互換
print(st.capitalize()) # 首字母大寫
輸出結(jié)果:
ABDEAJC KLM
abdeajc klm
AbdeaJC Klm
Abdeajc klm
-
刪除str字符串末尾空格
st = 'avd '
print(st.rstrip()) # 刪除字符末尾的空格
輸出結(jié)果:
avd
-
判斷str字符串是否只包含數(shù)字
# 判斷str字符串是否只包含數(shù)字
st = '1234567'
print(st.isnumeric())
# 如果 string 只包含數(shù)字則返回 True,否則返回 False.
返回結(jié)果:
True
-
判斷字符串是否至少有一個字符且所有字符都是字母
# 判斷字符串是否至少有一個字符且所有字符都是字母
st = 'DNVAK'
print(st.isalpha())
# 如果 string 至少有一個字符并且所有字符都是字母則返回 True,否則返回 False
輸出結(jié)果:
True
-
格式化字符——在字符串中插入變量
# 格式化字符——在字符串中插入變量
name = "FATBIRD"
truth = "%s is 好人" %name
print(truth)
# %s 表示我們這里要插入一個字符型的變瞪慧,%name代表這里我們插入name變量
# 所以髓考,要兩個%解決問題
x = 4
y = "hehe"
z = 4.2
print("this is %i" %x)
print("this is %s" %y)
print("this is %f" %z)
# %s %i %f都是格式化字符串,s/i/f分別代表插入字符串的源數(shù)據(jù)類型:字符型/整型/浮點型
輸出結(jié)果:
FATBIRD is 好人
this is 4
this is hehe
this is 4.200000
-
格式化字符串——數(shù)字格式化
# 格式化字符:數(shù)字格式化的那些坑
# 輸出2位小數(shù)
# %.2f弃酌,此處是四舍五入氨菇!
m = 3.1415926
print("pi is %f" %m)
print("pi is %.2f" %m)
print('---------------------------------')
# 注意:輸出整數(shù)與輸出整數(shù)型的區(qū)別
m = 10.6
print("pi is %.0f" %m)
# 10.6輸出整數(shù) → 11,此處四舍五入
print("pi is %i" %m)
# 10.6輸出整數(shù)型 → 10妓湘,此處不四舍五入查蓉,直接切掉小數(shù)部分
print('---------------------------------')
# 輸出科學(xué)計數(shù)形式
# 科學(xué)計數(shù)法 %e %E
m = 123.123123123
print("have fun %.2e" %m) # → 保留2位小數(shù)
print("have fun %.4E" %m) # → 保留4位小數(shù)
print('---------------------------------')
# 輸出數(shù)據(jù)顯示正負(fù)號,根據(jù)數(shù)字直接顯示
m = 100
print("have fun %+i" %m)
print("have fun %.2f" % -0.01)
print('---------------------------------')
# 自動識別數(shù)據(jù)輸出合適形式
m1 = 123.123123123
print("have fun %g" %m1) # → 數(shù)據(jù)復(fù)雜的時候自動識別用科學(xué)計數(shù)法
print("have fun %.2g" %m1) # → 注意與科學(xué)計數(shù)區(qū)別 %.2e → 表示保留2位小數(shù)榜贴,這里%.2g表示保留2位有效數(shù)字
m2 = 1.2
print("have fun %g" %m2) # → 小數(shù)位數(shù)少的時候自動識別用浮點數(shù)
輸出結(jié)果:
pi is 3.141593
pi is 3.14
---------------------------------
pi is 11
pi is 10
---------------------------------
have fun 1.23e+02
have fun 1.2312E+02
---------------------------------
have fun +100
have fun -0.01
---------------------------------
have fun 123.123
have fun 1.2e+02
have fun 1.2
三豌研、dict字典常用操作
dict字典,用{}標(biāo)識,是無序?qū)ο缶楣病S伤饕?key)和它對應(yīng)的值value組成鬼佣,key-value是成對出現(xiàn)的。dict是另一種可變?nèi)萜髂P图昂海铱纱鎯θ我忸愋蛯ο缶谌ぁW值涞拿總€鍵值(key=>value)對用冒號(:)分割,每個對之間用逗號(,)分割坷随,整個字典包括在花括號({})中房铭,鍵必須是唯一的,但值則不必温眉。
-
dict字典基本特征及創(chuàng)建
# 字典的創(chuàng)建
# 創(chuàng)建①直接手動書寫創(chuàng)建
# 手動書寫申明一個字典變量
dic = {'a':1,'b':2}
print(dic)
print('----------------------------')
# 創(chuàng)建②用函數(shù)dict()
dic = dict(m = 10 ,n = 'aa', h = [1,2,3])
print(dic)
print('----------------------------')
# 創(chuàng)建③生成序列再用dict()函數(shù)創(chuàng)建
# dict()由序列生成一個字典缸匪,嵌套序列,可以是list或者tuple
lst1=[("a","fff"),("b","ggg")]
lst2=[["c",1],["d",2]]
lst3=(("e",[1,2]),("f",[3,4]))
dic1 = dict(lst1)
dic2 = dict(lst2)
dic3 = dict(lst3)
print(dic1,dic2,dic3)
print('----------------------------')
# 創(chuàng)建④用dict.fromkeys()創(chuàng)建
# 只有key类溢,直接生成一個字典
keys = ["a", "b", "c"]
dic1 = dict.fromkeys(keys) # →返回的dict的value為None
dic2 = dict.fromkeys(keys, 'hello') # →返回的dict的value均為hello凌蔬,因為定義了value的值
print(dic1,dic2)
輸出結(jié)果:
{'a': 1, 'b': 2}
----------------------------
{'h': [1, 2, 3], 'm': 10, 'n': 'aa'}
----------------------------
{'a': 'fff', 'b': 'ggg'} {'d': 2, 'c': 1} {'e': [1, 2], 'f': [3, 4]}
----------------------------
{'a': None, 'b': None, 'c': None} {'a': 'hello', 'b': 'hello', 'c': 'hello'}
-
dict字典的添加、修改闯冷、刪除元素
# dict字典的添加砂心、修改、刪除元素
# 直接索引key進行添加蛇耀、修改辩诞、刪除
# 創(chuàng)建dict字典
dic = dict(m=1,n=2,c=5)
print(dic)
# 任意添加元素
dic['f'] = '添加一個值'
print(dic)
# 任意修改元素
dic['n'] = '任意修改其中一個值'
print(dic)
# 任意刪除元素
del dic['m']
print(dic)
輸出結(jié)果:
{'m': 1, 'c': 5, 'n': 2}
{'m': 1, 'f': '添加一個值', 'c': 5, 'n': 2}
{'m': 1, 'f': '添加一個值', 'c': 5, 'n': '任意修改其中一個值'}
{'f': '添加一個值', 'c': 5, 'n': '任意修改其中一個值'}
-
dict字典的刪除與清除
# dict字典的刪除與清除
# 創(chuàng)建dict字典
dic = dict(m=1,n=2,c=5)
print(dic)
# .clear()清除字典元素
dic.clear()
print(dic)
# 用del語句刪除整個字典
del dic
#print(dic) 整個字典已刪除,無返回值/若print直接報錯
輸出結(jié)果:
{'m': 1, 'c': 5, 'n': 2}
{}
-
dict字典更新/合并
# 更新/合并字典
# dict.update()
dic1 = {"a":1, "b":2}
dic2 = {"c":3, "d":4}
print(dic1)
print(dic2)
dic1.update(dic2)
print(dic1,dic2)
# 把第二個字典dic2合并到第一個字典dic纺涤,改變了第一個字典
# 第二個字典不變
輸出結(jié)果:
{'a': 1, 'b': 2}
{'d': 4, 'c': 3}
{'a': 1, 'b': 2, 'c': 3, 'd': 4} {'d': 4, 'c': 3}
-
dict字典復(fù)制
# 復(fù)制字典
# .copy(),復(fù)制一個新字典
a = {'m':1 , 'n':2 , 'p':3}
b = a.copy()
a.update({'q':4})
print('修改后的a字典:',a)
print('b字典不受影響',b)
輸出結(jié)果:
修改后的a字典: {'m': 1, 'q': 4, 'p': 3, 'n': 2}
b字典不受影響 {'m': 1, 'n': 2, 'p': 3}
-
dict字典成員判斷:in/not in
# 字典成員判斷:in/not in
# 字典的判斷是否包含译暂,須用key作為判斷對象
a = {'m':1 , 'n':2 , 'p':3}
print(a)
print('m' in a)
print(1 in a) # 這里判斷1是否存在字典a中,但是1不是字典a的key撩炊,因此返回False
輸出結(jié)果:
{'m': 1, 'p': 3, 'n': 2}
True
False
-
dict字典的元素訪問
# dict字典元素的訪問
# dict字典單個元素訪問——索引key訪問
# 因字典沒有順序外永,以key來作為指向,所以指向的key必須存在
# 注意dict字典的索引與list的索引方式不同拧咳,字典是索引key
dic = {'a':1, "b":2, "c":3}
print(dic['a'])
print('--------------------------------------------')
# 嵌套字典的單個元素訪問
# 對于嵌套字典伯顶,輸出嵌套內(nèi)容,通過重復(fù)指向來輸出
poi = {'name':'shop', 'city':'shanghai', 'information':{'address':'somewhere', 'num':66663333}}
print(poi['information']['address'])
# 索引key=information的元素骆膝,再訪問這個元素key=address的元素值 → somewhere
print('--------------------------------------------')
# 用get直接訪問字典單個元素
# .get(key)方法:直接查看key的value
# 如果沒有相應(yīng)key則返回None祭衩,添加print參數(shù)可以多返回一個值
print(poi.get('name'))
print(poi.get('information'))
print(poi.get('type',print('nothing')))
print('--------------------------------------------')
# .keys()方法,訪問字典所有key
# 輸出內(nèi)容格式為視圖谭网,可以用list()得到key的列表汪厨,類似range()
print(poi.keys(),type(poi.keys()))
print(list(poi.keys()))
print('--------------------------------------------')
# .values()方法,訪問字典所有value
# 輸出內(nèi)容格式為視圖愉择,可以用list()得到value的列表劫乱,類似range()
print(poi.values(),type(poi.values()))
print(list(poi.values()))
print('--------------------------------------------')
# .items()方法织中,訪問字典所有items(元素)
# 輸出內(nèi)容格式為視圖,可以用list()得到items的列表衷戈,類似range()
print(poi.items(),type(poi.items()))
print(list(poi.items()))
輸出結(jié)果:
1
--------------------------------------------
somewhere
--------------------------------------------
shop
{'num': 66663333, 'address': 'somewhere'}
nothing
None
--------------------------------------------
dict_keys(['information', 'city', 'name']) <class 'dict_keys'>
['information', 'city', 'name']
--------------------------------------------
dict_values([{'num': 66663333, 'address': 'somewhere'}, 'shanghai', 'shop']) <class 'dict_values'>
[{'num': 66663333, 'address': 'somewhere'}, 'shanghai', 'shop']
--------------------------------------------
dict_items([('information', {'num': 66663333, 'address': 'somewhere'}), ('city', 'shanghai'), ('name', 'shop')]) <class 'dict_items'>
[('information', {'num': 66663333, 'address': 'somewhere'}), ('city', 'shanghai'), ('name', 'shop')]
-
dict字典元素的遍歷
# 字典的元素遍歷
# 用 for ..in 語句遍歷字典元素
poi = {'name':'shop', 'city':'shanghai', 'information':{'address':'somewhere', 'num':66663333}}
for key in poi.keys(): # 遍歷key
print(key)
print('-------')
for value in poi.values(): # 遍歷values
print(value)
print('-------')
for (k,v) in poi.items(): #遍歷items(條目)
print('key為 %s, value為 %s' %(k,v))
輸出結(jié)果:
information
city
name
-------
{'num': 66663333, 'address': 'somewhere'}
shanghai
shop
-------
key為 information, value為 {'num': 66663333, 'address': 'somewhere'}
key為 city, value為 shanghai
key為 name, value為 shop
四狭吼、條件及循環(huán)語句
4.1條件語句if
Python條件語句是通過一條或多條語句的執(zhí)行結(jié)果(True或者False)來決定執(zhí)行的代碼塊。
-
基本判斷語句 if
# 基本判斷語句
age = 12
if age < 18:
print('18歲以下不宜觀看')
# if語句后面必須有 :
# 自動縮進
# if語句寫完后殖妇,要退回原有縮進繼續(xù)寫
# Python代碼的縮進規(guī)則:具有相同縮進的代碼被視為代碼塊
輸出結(jié)果:
18歲以下不宜觀看
-
兩種條件判斷 if-else
# 兩種條件判斷:if-else
flag = False
name = 'luren'
if name == 'python': # 判斷變量否為'python'
flag = True # 條件成立時設(shè)置標(biāo)志為真
print( 'welcome boss') # 并輸出歡迎信息
else:
print(name) # 條件不成立時輸出變量名稱
輸出結(jié)果:
luren
-
多種條件判斷 if-elif-...-else
# 多種條件判斷:if-elif-...-else
num = 2
if num == 3: # 判斷num的值
print('boss')
elif num == 2:
print('user')
elif num == 1:
print('worker')
elif num < 0: # 值小于零時輸出
print('error')
else:
print('roadman') # 條件均不成立時輸出
輸出結(jié)果:
user
-
單語句多條件判斷 or與and
# 單語句多條件判斷:or and
num = 5
if num >= 0 and num <= 10:
print( 'hello')
# 判斷值是否在0~10之間
# 輸出結(jié)果: hello
num = 10
if num < 0 or num > 10:
print( 'hello')
else:
print( 'undefine')
# 判斷值是否在小于0或大于10
# 輸出結(jié)果: undefine
num = 8
if (num >= 0 and num <= 5) or (num >= 10 and num <= 15):
print( 'hello')
else:
print( 'undefine')
# 判斷值是否在0~5或者10~15之間
# 輸出結(jié)果: undefine
輸出結(jié)果:
hello
undefine
undefine
4.2循環(huán)語句
-
循環(huán)語句:for循環(huán)
for循環(huán)可以遍歷任何序列的項目刁笙,如一個列表或者一個字符串。for循環(huán)再序列中迭代谦趣。
- for循環(huán)基本特征:
# 輸出 hello world 5次
for i in range(5):
print('hello world')
輸出結(jié)果:
hello world
hello world
hello world
hello world
hello world
- for循環(huán)遍歷序列疲吸、字典映射:
# 遍歷序列
lst = list(range(10))
print(lst)
for i in lst: # 遍歷整個lst
print(i)
print('----------------------------')
for i in lst[::2]: # 按步長為2遍歷整個lst
print(i)
print('----------------------------')
print('----------------------------')
# 遍歷字典
dic = dict(m=1,n=4,j=10)
print(dic)
for i in dic.keys(): # 遍歷key
print(i)
print('----------------------------')
for i in dic.values(): # 遍歷value
print(i)
print('----------------------------')
for (k,v) in dic.items(): # 遍歷items
print((k,v))
輸出結(jié)果:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0
1
2
3
4
5
6
7
8
9
----------------------------
0
2
4
6
8
----------------------------
----------------------------
{'m': 1, 'j': 10, 'n': 4}
m
j
n
----------------------------
1
10
4
----------------------------
('m', 1)
('j', 10)
('n', 4)
- 嵌套循環(huán),盡量不要多于3個嵌套:
# 嵌套循環(huán)
for i in range(3):
for j in range(4):
print(i,j)
輸出結(jié)果:
0 0
0 1
0 2
0 3
1 0
1 1
1 2
1 3
2 0
2 1
2 2
2 3
-
循環(huán)語句:while
執(zhí)行語句可以是單個語句或語句塊前鹅,判斷條件可以是任何表達(dá)式摘悴,任何非零、或非空(null)的值均為true舰绘。當(dāng)判斷條件假false時蹂喻,循環(huán)結(jié)束。
- 循環(huán)語句while的基本邏輯:
# 基本運行邏輯
count = 0
while count < 9:
print( 'The count is:', count)
count = count + 1
print( "Good bye!")
# 這里count<9是一個判斷語句捂寿,當(dāng)判斷為True時口四,則繼續(xù)運行
輸出結(jié)果:
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
- 使用while時須注意,要避免無限循環(huán)的出現(xiàn):
# 關(guān)于無限循環(huán):如果條件判斷語句永遠(yuǎn)為 true秦陋,循環(huán)將會無限的執(zhí)行下去
var = 1
while var == 1 :
num = input("Enter a number :")
print( "You entered: ", num)
print( "Good bye!")
# 該條件永遠(yuǎn)為true蔓彩,循環(huán)將無限執(zhí)行下去
# 一定要避免無限循環(huán)!踱侣!
- while-else語句粪小,邏輯使用與if-else一樣:
# while-else語句
count = 0
while count < 5:
print(count, " is less than 5")
count = count + 1
else:
print(count, " is not less than 5")
# 邏輯和 if-else 一樣
輸出結(jié)果:
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
-
循環(huán)控制語句
循環(huán)控制語句有:
→ break:在語句塊執(zhí)行過程中終止循環(huán)大磺,并且跳出整個循環(huán)
→ continue:在語句塊執(zhí)行過程中跳出該次循環(huán)抡句,執(zhí)行下一次循環(huán)
→ pass:pass是空語句,是為了保持程序結(jié)構(gòu)的完整性
- break語句:
# break語句
s = 0
n = 1
while n > 0:
s = s + n
n = n + 1
if n == 20:
break
print(s)
# break語句用來終止循環(huán)語句杠愧,即便循環(huán)條件沒有False條件或者序列還沒被完全遞歸完待榔,也會停止執(zhí)行循環(huán)語句。
s = 0
for i in range(10):
for j in range(5):
s = s + (i*j)
print('第%i次計算' %(i+j))
if s > 20:
break
print('結(jié)果為%i' % s)
# 如果使用嵌套循環(huán)流济,break語句將停止執(zhí)行最深層的循環(huán)锐锣,并開始執(zhí)行下一行代碼。
輸出結(jié)果:
190
第0次計算
第1次計算
第2次計算
第3次計算
第4次計算
第1次計算
第2次計算
第3次計算
第4次計算
第5次計算
第2次計算
第3次計算
第4次計算
第5次計算
第6次計算
結(jié)果為30
- continue語句:
# continue語句
s = 0
for i in range(50):
if i%2 == 0:
s += i
else:
continue
print('第%i次計算'%(i/2))
print('結(jié)果為%i' % s)
# continue 語句用來告訴Python跳過當(dāng)前循環(huán)的剩余語句绳瘟,然后繼續(xù)進行下一輪循環(huán)雕憔。
輸出結(jié)果:
第0次計算
第1次計算
第2次計算
第3次計算
第4次計算
第5次計算
第6次計算
第7次計算
第8次計算
第9次計算
第10次計算
第11次計算
第12次計算
第13次計算
第14次計算
第15次計算
第16次計算
第17次計算
第18次計算
第19次計算
第20次計算
第21次計算
第22次計算
第23次計算
第24次計算
結(jié)果為600
- pass語句:
# pass語句
for letter in 'Python':
if letter == 'h':
pass
print( '當(dāng)前字母 : h,但是我pass了')
print( '當(dāng)前字母 :', letter)
print( "Good bye!")
# pass是空語句糖声,是為了保持程序結(jié)構(gòu)的完整性斤彼。(不中斷也不跳過)
輸出結(jié)果:
當(dāng)前字母 : P
當(dāng)前字母 : y
當(dāng)前字母 : t
當(dāng)前字母 : h分瘦,但是我pass了
當(dāng)前字母 : h
當(dāng)前字母 : o
當(dāng)前字母 : n
Good bye!
五、函數(shù)
在一些情況下琉苇,會發(fā)現(xiàn)自己編寫函數(shù)比使用Python內(nèi)置函數(shù)和安裝別人開發(fā)的模塊更方便有效嘲玫。當(dāng)一些情況需要不斷重復(fù)看書寫同樣的代碼片段,那么就應(yīng)該考慮將這個代碼片段轉(zhuǎn)為函數(shù)并扇。
-
自定義函數(shù)
在pyhton中創(chuàng)建函數(shù)去团,使用def關(guān)鍵字:
# 定義函數(shù)
def f(x):
if x < 5:
print('輸入值小于5')
else:
print('輸入值大于等于5') # 定義函數(shù),其中x是參數(shù)(局部變量)
f(10) # 運行函數(shù)
輸出結(jié)果:
輸入值大于等于5
- 函數(shù)運行后穷蛹,最后需要返回一個或多個值土陪,可以使用return關(guān)鍵字來返回函數(shù)結(jié)果供程序使用。
# 關(guān)于retuen
# return語句退出函數(shù)肴熏,并返回一個表達(dá)式旺坠。不帶參數(shù)值的return語句返回None
def f1(x):
y = 2**x # 沒有return
def f2(x):
y = 2**x
return y # 含有return
print(f1(2),f2(2))
輸出結(jié)果:
None 4
- 默認(rèn)參數(shù)與可變參數(shù):
# 默認(rèn)參數(shù)
def f(x,n = 2):
return(x**n)
print(f(10))
print(f(10,3))
print('---------')
# n = 2,這里n的默認(rèn)值為2,如果不輸入則以默認(rèn)值為主
# 可變參數(shù)
# 通過*來定義可變參數(shù)
def f(*x):
print(x)
return x
f(1)
f('a','b')
f(1,2,3,[44,33])
print(type(f('a','b')))
# 默認(rèn)會把可變參數(shù)傳入一個元祖
輸出結(jié)果:
100
1000
---------
(1,)
('a', 'b')
(1, 2, 3, [44, 33])
('a', 'b')
<class 'tuple'>
-
輸入函數(shù) input()
input() 函數(shù)接受一個標(biāo)準(zhǔn)輸入數(shù)據(jù)扮超,返回為 string 類型取刃。
# 輸入函數(shù) input()
# 注意:input()返回結(jié)果都為字符串,如果需要變?yōu)閿?shù)字則用到int()/float()
score = input('請輸入成績:')
print('該學(xué)生成績?yōu)椋? + score)
print(type(score))
輸出結(jié)果:
請輸入成績:90
該學(xué)生成績?yōu)椋?0
<class 'str'>
-
局部變量及全局變量
定義在函數(shù)內(nèi)部的變量擁有一個局部作用域出刷,定義在函數(shù)外的擁有全局作用域璧疗。
局部變量只能在其被聲明的函數(shù)內(nèi)部訪問,而全局變量可以在整個程序范圍內(nèi)訪問馁龟。調(diào)用函數(shù)時崩侠,所有在函數(shù)內(nèi)聲明的變量名稱都將被加入到作用域中。
- 局部變量與全局變量的區(qū)別:
def f(m):
m = '呵呵噠' # 函數(shù)作用:把輸入變量指向“呵呵噠”
print("函數(shù)內(nèi)為局部變量:%s" % m)
a = input('請輸入一個數(shù)字:')
f(a)
print("函數(shù)外為全局變量:%s" % a)
# f(m)中坷檩,m是函數(shù)的參數(shù)却音,f(x)是吧x的值賦予了m,但x值自己本身不受影響矢炼,所以執(zhí)行函數(shù)后系瓢,是在函數(shù)局部“變化”了x
# 什么是局部變量? → 當(dāng)函數(shù)定義內(nèi)聲明變量的時候句灌,它們與函數(shù)外具有相同名稱的其他變量沒有任何關(guān)系!
# 即變量名稱對于函數(shù)來說是“局部”的夷陋。這稱為變量的作用域。所有變量的作用域是它們被定義的塊胰锌,從它們的名稱被定義的那點開始骗绕。
輸出結(jié)果:
請輸入一個數(shù)字:8
函數(shù)內(nèi)為局部變量:呵呵噠
函數(shù)外為全局變量:8
- 局部變量轉(zhuǎn)化為全局變量:
# global語句 → 把局部變量變?yōu)槿肿兞?
def f():
global a
a = '呵呵噠'
print("函數(shù)內(nèi)轉(zhuǎn)為全局變量:%s" % a)
a = input('請輸入一個數(shù)字:')
print("輸入變量值:%s" % a)
f()
# 后一個f()應(yīng)該是全局變量,可輸出的結(jié)果是局部變量的
# 因使用了globa語句將局部變量變?yōu)槿肿兞?
輸出結(jié)果:
請輸入一個數(shù)字:10
輸入變量值:10
函數(shù)內(nèi)轉(zhuǎn)為全局變量:呵呵噠
-
匿名函數(shù)Lambda
# lambda 語句創(chuàng)建匿名函數(shù)
def fun(a,b,c):
return a+b+c
print(fun(2,3,4))
# def創(chuàng)建自定義函數(shù)资昧,求和
f = lambda a,b,c:a+b+c
print(f(2,3,4))
# lambda作為匿名函數(shù)酬土,是不需要函數(shù)名的 → 需要一個函數(shù),又不想動腦筋去想名字格带,這就是匿名函數(shù)
# lambda的主體是一個表達(dá)式撤缴,而不是一個代碼塊东揣。
# lambda只有一行,僅僅能在lambda表達(dá)式中封裝有限的邏輯進去腹泌。
輸出結(jié)果:
9
9
六嘶卧、模塊與包
Python模塊(Module),是一個 Python文件凉袱,以.py 結(jié)尾芥吟,包含了Python對象定義和Python語句。
-
調(diào)用模塊語句
調(diào)用模塊語句:import
# 調(diào)用模塊語句:import
import numpy # 這里調(diào)用了numpy
a = numpy.random.rand(5)
print(a)
輸出結(jié)果:
[ 0.28750147 0.12144201 0.03357802 0.04839461 0.04384718]
- 簡化模塊名:import...as...
為了方便書寫专甩,調(diào)用模塊可以簡化模塊的名稱钟鸵。
# 簡化模塊名:import...as...
import numpy as np
a = np.random.rand(5)
print(a)
# 簡化模塊名
輸出結(jié)果:
[ 0.2425978 0.73225087 0.73194903 0.93775474 0.61022389]
- 調(diào)用部分模塊語句:from…import 語句
→ 單獨導(dǎo)入模塊的部分功能,但無法使用其他未導(dǎo)入模塊功能
-
模塊路徑問題
# 模塊路徑問題
import pandas
print(pandas.__file__)
# 查看現(xiàn)有包所在路徑涤躲,可以將自己創(chuàng)建的包存入改路徑
#import sys
#sys.path.append(路徑)
# 加載sys包棺耍,把新建的包所在路徑添加上
-
python標(biāo)準(zhǔn)模塊
random隨機數(shù)
# python標(biāo)準(zhǔn)模塊 —— random隨機數(shù)
import random # 調(diào)用random模塊
x = random.random()
y = random.random()
print(x,y*10)
print('-----------------------')
# random.random()隨機生成一個[0:1)的隨機數(shù)
m = random.randint(0,10)
print(m)
print('-----------------------')
# random.randint()隨機生成一個[0:10]的整數(shù)
st1 = random.choice(list(range(10)))
st2 = random.choice('abcdnehgjla')
print(st1,st2)
print('-----------------------')
# random.choice()隨機獲取()中的一個元素,()種必須是一個有序類型
lst = list(range(20))
sli = random.sample(lst,5)
print(sli)
print('-----------------------')
# random.sample(a,b)隨機獲取a中指定b長度的片段种樱,不會改變原序列
lst = [1,3,5,7,9,11,13]
random.shuffle(lst)
print(lst)
# random.shuffle(list)將一個列表內(nèi)的元素打亂
輸出結(jié)果:
0.3599048616357652 1.564509077366436
-----------------------
7
-----------------------
7 l
-----------------------
[18, 16, 15, 14, 8]
-----------------------
[1, 9, 7, 11, 3, 13, 5]
- time時間模塊
# python標(biāo)準(zhǔn)模塊 —— time時間模塊
import time # 調(diào)用time模塊
for i in range(2):
print('hello')
time.sleep(1)
print('-----------------------')
# time.sleep()程序休息()秒
print(time.ctime())
print(type(time.ctime()))
print('-----------------------')
# time.ctime(),將當(dāng)前時間轉(zhuǎn)換為一個字符串
print(time.localtime())
print(type(time.localtime()))
print('-----------------------')
# time.localtime(),將當(dāng)前時間轉(zhuǎn)為當(dāng)前時區(qū)的struct_time
# wday 0-6表示周日到周六
# ydat 1-366 一年中的第幾天
# isdst 是否為夏令時蒙袍,默認(rèn)為-1
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
# time.strftime(a,b)
# a為格式化字符串格式
# b為時間戳,一般用localtime()
輸出結(jié)果:
hello
hello
-----------------------
Sun Nov 10 13:09:14 2019
<class 'str'>
-----------------------
time.struct_time(tm_year=2019, tm_mon=11, tm_mday=10, tm_hour=13, tm_min=9, tm_sec=14, tm_wday=6, tm_yday=314, tm_isdst=0)
<class 'time.struct_time'>
-----------------------
2019-11-10 13:09:14
七嫩挤、數(shù)據(jù)讀寫
-
文件對象聲明及基本操作
路徑書寫格式:
# 路徑書寫格式
# 本地文件的界定:指向一個本地存儲的文件害幅,是一個鏈接或者一個映射
path1 = 'C:/Users/Hjx/Desktop/text.txt'
# 單個反斜杠:/
path2 = 'C:\\Users\\Hjx\\Desktop\\text.txt'
# 兩個斜杠:\\(第一個\是轉(zhuǎn)義符)
path3 = r'C:\Users\Hjx\Desktop\text.txt'
# r用于防止字符轉(zhuǎn)義
print(path1)
print(path2)
print(path3)
輸出結(jié)果:
C:/Users/Hjx/Desktop/text.txt
C:\Users\Hjx\Desktop\text.txt
C:\Users\Hjx\Desktop\text.txt
- 讀寫文件語句:
# 讀取文件:open語句
# open('路徑', '模式', enconding = '編碼' )
# 模式:r:讀取文件,默認(rèn)岂昭;w:寫入以现;rw:讀取+寫入;a:追加
# 存儲編碼:'utf8';'gbk'
# .read() 讀取文件內(nèi)容约啊,讀取后邑遏,光標(biāo)將會留在讀取末尾
path2 = 'C:\\Users\\Hjx\\Desktop\\text.txt'
f = open(path2, 'r') # 打開文件text.txt
print(type(f))
print(f)
print(f.read())
print('讀取完畢')
# 因為用.read()讀取文件內(nèi)容后,光標(biāo)留在讀取末尾
# 所以現(xiàn)在用 f.seek(0) 來移動光標(biāo)
f.seek(0)
print(f.read())
print('第二次讀取')
# 用f.readline()按行讀取
f.seek(0)
f.readline(10) # 讀取一行中的前10個字符
# 利用for循環(huán)語句遍歷按照行遍歷文件
f.seek(0)
for line in f.readlines():
print(line,type(line))
f.close()
# print(f.read()) # 關(guān)閉后無法讀取
# 關(guān)閉文件鏈接 f.close()恰矩,養(yǎng)成一個好習(xí)慣
-
os模塊
OS模塊屬于系統(tǒng)模塊记盒,提供了非常豐富的方法用來處理文件和目錄。
- os模塊常用操作:
# os模塊:系統(tǒng)模塊 - 常用命令
import os # 導(dǎo)入模塊
# os.name,輸出字符串指示正在使用的平臺
# 如果是window 則用'nt'表示枢里,Linux/Unix用戶孽鸡,它是'posix'
print(os.name)
# os.getcwd()蹂午,得到當(dāng)前工作目錄栏豺,即當(dāng)前Python腳本工作的目錄路徑。
print(os.getcwd())
# os.listdir()豆胸,返回指定目錄下的所有文件和目錄名奥洼。
print(os.listdir())
#os.chdir(路徑) → 切換到指定的目標(biāo)路徑
os.chdir('C:\\Users\\Hjx\\Desktop\\' )
# os.remove(),刪除()里的文件
os.remove('text2.txt')
# os.path.split(),返回()里路徑的目錄名和文件名
print(os.path.split('C:\\Users\\Hjx\\Desktop\\text.txt'))
# os.path.exists(路徑)
# 用來檢驗給出的路徑是否真地存在
print(os.path.exists('C:\\Users\\Hjx\\Desktop\\heheh.txt'))
print(os.path.exists('C:\\Users\\Hjx\\Desktop\\'))
# 這里的hehe.txt文件不存晚胡,返回False灵奖,但是路徑卻是存在的嚼沿,故返回True
*相對路徑與絕對路徑:
#【相對路徑和絕對路徑】
f=open(r'C:\Users\Yeung\Desktop\test.txt','r',encoding='utf8') # 這個是絕對路徑
f.read()
f.seek(0)
f.close()
#相對路徑
#os.chdir(r'E:\py') # os.chdir()切換至指定目錄
#f2=open('test.txt','r',encoding='utf8') # os.chdir()已經(jīng)申明指定目錄,所以這里可以直接open文件名+模式+編碼
#f2.read()
#f2.seek(0)
#f2.close()
- os模塊下的文件讀取與文件寫入:
#【os模塊下的文件讀取】
os.chdir(r'C:\Users\Yeung\Desktop') # os.chdir()切換至指定目錄
f=open('test.txt','r',encoding='utf8')
f.read(10) # 只讀取前10個字符
f.readline() # 按行讀取
f.seek(0)
f.readline(10) # 讀取一行中的前10個字符
# 利用for循環(huán)語句遍歷按照行遍歷文件
f.seek(0)
for line in f.readlines():
print(line,type(line))
print('------------------')
#【文件寫入】
path=r'C:\Users\Yeung\Desktop\write.txt'
f = open(path,'w',encoding='utf8')
f.writelines('hello world')
f.close()
# 文件寫入自動換行
f=open(path,'w',encoding='utf8')
lst=['a','b','c']
for i in range(len(lst)):
lst[i]=lst[i]+'\n'
print(lst[i])
f.writelines(lst)
f.close()
-
pickle模塊
→ pickle提供了一個簡單的持久化功能瓷患÷饩。可以將對象以文件的形式存放在磁盤上。python的pickle模塊實現(xiàn)了基本的數(shù)據(jù)序列和反序列化擅编。
→ 通過pickle模塊的序列化操作我們能夠?qū)⒊绦蛑羞\行的對象信息保存到文件中去攀细,永久存儲。
→ 通過pickle模塊的反序列化操作爱态,我們能夠從文件中創(chuàng)建上一次程序保存的對象谭贪。
# pickle 模塊
# 用pickle模塊存儲的文件不會改變數(shù)據(jù)結(jié)構(gòu)
# 【將下來生成的字典存儲為.pkl文件,即系序列化】
# 第一步 導(dǎo)入pickle模塊
import pickle
# 第二步 創(chuàng)建一個字典
dic=dict(a=1,b=2,c=3,d=4,e=5)
print(dic)
# 第三步 打開一個.pkl文件
pic = open(r'C:\Users\Yeung\Desktop\data.pkl','wb') # 填寫要存儲的路徑+文件名锦担,存儲模式:以二進制來存儲:rb, wb, wrb, ab
# 第四步 用 pickle.dump() 將字典存儲到data,pkl的文件中
pickle.dump(dic,pic) # 將字典dic存到路徑pic目錄下 ()中參數(shù)俭识,第一個是寫入的內(nèi)容,第二是寫入的格式
pic.close()
print('------------')
#【將存儲的.plk文件讀取出來洞渔,即系反序列化】
# 第一步 打開.plk文件
f=open(r'C:\Users\Yeung\Desktop\data.pkl','rb')
# 第二步 用pickle.load()讀取.pkl文件
print(pickle.load(f))