小白學python3

一、函數的內嵌和閉包
1.函數的內嵌就是一個函數裏面包含着另一個函數。
正常函數

>>> def MyFun():
	global count
	count=10
	print(count)

	
>>> MyFun()
10

內嵌函數

>>> def fun1():
	print('fun1()正在被調用')
	def fun2():
		print('fun2()正在被調用')
	fun2()
>>> fun1()
fun1()正在被調用
fun2()正在被調用
>>> 

2.閉包(由外而內,由大而小,函數式編程)

>>> def fun1():
	x=5   //此時的x對於fun2()來說是外部值,不可引用,除非是容器型的纔可以賦值給fun2()
	def fun2():
		x*=x
		return x
	return fun2()

>>> fun1()    //此時調用fun1()會出現錯誤,因爲fun2()爲內部函數,在不調用fun1()時,fun2()不會被賦值

上面的代碼改編1:

>>> def fun1():
	x=[5]  //此時的x是容器型的可以給fun2()f賦值
	def fun2():
		x[0]*=x[0]
		return x[0]
	return fun2()

>>> fun1()
25

改編2:

>>> def fun1():
	x=5
	def fun2():
		nonlocal x    //此時把x定義成了全局變量
		x*=x
		return x
	return fun2()

>>> fun1()
25

內部函數和外部函數的調用

>>> def FunX(x):
	def FunY(y):
		return x*y
	return FunY
>>> i=FunX(8)
>>> type(i)      //此時i的類型是“函數”
<class 'function'>
>>> i(5)
40
>>> FunX(3)(2)  //此時賦值x=3,y=2
6

二、lambda表達式
例1.

>>> def ds(x):
	return 2*x+1

>>> ds(5)
11

等價於

>>> lambda x:2*x+1   //冒號前面表示變量名字,後面表示對該變量的操作
<function <lambda> at 0x0000000002FEC6A8>
>>> g=lambda x:2*x+1
>>> g(5)
11

例2.

>>> def add(x,y):
	return x+y

>>> add(3,4)
7

等價於

>>> g=lambda x,y:x+y
>>> g(3,4)
7
>>> 

總結:使用lambda的優點是1.省下定義過程2.不用起變量的名字3.可讀性比較強
三、兩個牛逼的BIF
1.過濾函數filter(參1,參2)
參1表示過濾法則(一般過濾掉False和≤0的數),參2表示過濾範圍

>>> def odd(x):
	return x%2  ///取餘之後的值非0及1

>>> temp=range(10)
>>> show=filter(odd,temp)  //篩選出範圍內所有的奇數
>>> list(show)
[1, 3, 5, 7, 9]

上面函數等價於

>>> list(filter(lambda x:x%2,range(10)))
[1, 3, 5, 7, 9]

2.map(參1,參2)映射函數
其中參1表示運算法則,參2表示源數據,而map()將參2的源數據引入參1的運算法則

>>> list(map(lambda x:x*2,range(10)))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> 

四、遞歸(漢諾塔、樹結構、謝爾賓斯基三角形)
遞歸就是函數調用自身
典例1.求階乘
法1:用傳統的方法

>>> def fac(n):
	result=n
	for i in range(1,n):
		result*=i
	return result

>>> fac(5)
120

法2:用遞歸

>>> def fac(n):
	if n==1:
		return 1
	else:
		return n*fac(n-1)
>>> fac(5)
120

遞歸求階乘思維圖在這裏插入圖片描述
典例2.求斐波那契數列
在這裏插入圖片描述
法1:迭代

>>> def fab(n):
	n1=1
	n2=1
	n3=1
	if n<1:
		prunt('輸入有誤')
		return -1
	while (n-2)>0:
		n3=n1+n2
		n1=n2
		n2=n3
		n-=1
	return n3

>>> fab(1)
1
>>> fab(2)
1
>>> fab(3)
2
>>> fab(4)
3

法2:遞歸

>>> def fab(n):
	if n<1:
		print('輸入有誤')
		return -1
	if n==1 or n==2:
		return 1
	else:
		return fab(n-1)+fab(n-2)

	
>>> fab(1)
1
>>> fab(2)
1
>>> fab(3)
2
>>> fab(4)
3
>>> fab(5)
5

典例3.漢諾塔
求解出玩漢諾塔遊戲的攻略,即移動路線

def han(n,x,y,z):     //定義函數
    if n==1:
        print(x,'->',z)
    else:
        han(n-1,x,z,y)
        print(x,'->',z)
        han(n-1,y,x,z)

n=int(input('請輸入漢諾塔的層數')) //調用函數
han(n,'X','Y','Z')

調用結果:

============== RESTART: C:/ProgramData/Anaconda3/Scripts/han.py ==============
請輸入漢諾塔的層數3 
X -> Z
X -> Y
Z -> Y
X -> Z
Y -> X
Y -> Z
X -> Z
>>> 

總結:遞歸在求解某些特定結構時(漢諾塔)是有優勢的,而平常的問題比如斐波那契數列的求解中就可以看出來,遞歸耗時長,迭代速度更快!
五、字典(由鍵和值組成,Key–Values)
1.一般結構

>>> dict1={'李寧':'一切皆有可能','耐克':'just do it',' 阿迪達斯':'impossible is nothing'}
//字典結構使用中括號,每個鍵值對之間用逗號隔開,一組鍵值對之間用冒號
>>> print('李寧的口號是:',dict1['李寧'])
李寧的口號是: 一切皆有可能
>>>

2.調用方式

>>> dict2={1:'one',2:'two',3:'three'}
>>> dict2[2] //調用時【】裏輸入要調用的‘’鍵‘’
'two'

3.定義方式

>>> dict3=dict((('F',70),('i',105)))
>>> dict3
{'F': 70, 'i': 105}
>>> dict4=dict(小魚='我好餓',愛迪生='我也好餓')
>>> dict4
{'小魚': '我好餓', '愛迪生': '我也好餓'}
>>> dict4['愛迪生']
'我也好餓'
>>> 

4.訪問字典的方法-----keys(),values(),items()

>>> dict1={}
>>> dict1=dict1.fromkeys(range(32),'贊')
>>> dict1
{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: '贊', 25: '贊', 26: '贊', 27: '贊', 28: '贊', 29: '贊', 30: '贊', 31: '贊'}
>>> 
>>> dict1={}
>>> dict1=dict1.fromkeys(range(32),'贊')
>>> for eachkey in dict1.keys():
	print(eachkey) //依次顯示每個鍵

	
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
25
26
27
28
29
30
31
>>> 
>>> for eachvalue in dict1.values(): 
	print(eachvalue) //依次顯示每個值

	
贊
贊
贊
贊
贊
贊
贊
贊
贊
贊
贊
贊
贊
贊
贊
贊
贊
贊
贊
贊
贊
贊
贊
贊
贊
贊
贊
贊
贊
贊
贊
贊
>>> 
>>> for eachitem in dict1.items():
	print(eachitem) //依次顯示每個項

	
(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, '贊')
(25, '贊')
(26, '贊')
(27, '贊')
(28, '贊')
(29, '贊')
(30, '贊')
(31, '贊')
>>> 
>>> dict1.clear()   //清空一個字典
>>> dict1
{}
>>> 
>>> dict1={1:'one',2:'two',3:'three'}
>>> dict1.pop(1)    //刪除一個鍵
'one'
>>> dict1
{2: 'two', 3: 'three'}
>>> a={}
>>> a.setdefault('小白')         //在字典中加入單個項
>>> a.setdefault(5,'five')
'five'
>>> a
{'小白
>>> a={}
>>> a.setdefault('小白')
>>> a.setdefault(5,'five')
'five'
>>> a
{'小白': None, 5: 'five'}
>>> b={'小白':'狗'}
>>> a.update(b)  //用一個單個項的字典來更新舊的字典
>>> a
{'小白': '狗', 5: 'five'}
>>> 

六、集合(元素具有唯一性、無序性,用中括號表示)
1.創建
法1

>>> num2={1,2,3,3,5,0,9,7,3,1,2} //創建一個無序的有重複項的集合,存儲時會去掉重複項
>>> num2
{0, 1, 2, 3, 5, 7, 9}
>>> 

法2:使用set函數

>>> set1=set([1,2,3,4,5,5,3])
>>> set1
{1, 2, 3, 4, 5}
>>> 

2.典例:去掉重複的元素【1,2,3,4,5,5,3,1,0】
法1:

>>> num1=[1,2,3,4,5,5,3,1,0]
>>> temp=[]
>>> for each in num1:
	if each not in temp:
		temp.append(each)
>>> temp
[1, 2, 3, 4, 5, 0]
>>> 

法2:

>>> num1=list(set(num1))
>>> num1
[0, 1, 2, 3, 4, 5]
>>> 

2:集合中添加元素

>>> num2={1,2,3,4,5}
>>> num2.add(6)
>>> num2
{1, 2, 3, 4, 5, 6}
>>> 

3:使集合不可變—frozen

>>> num3=frozenset([1,2,3,4])
>>> num3.add(5)
Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    num3.add(5)
AttributeError: 'frozenset' object has no attribute 'add'  //此時拋出異常顯示frozen沒有add這個功能
>>> 

七、文件
1.文件對象方法
在這裏插入圖片描述

>>> f=open('F:\\record.txt')   //注意等號
>>> f.read()        //全部讀取
''
>>> f.close()   //不用文件及時關閉,養成個好習慣
>>> f=open('f:\\record.txt')
>>> f.read()
'我好餓呀呀呀\n'
>>> f.read(2)   //只讀取2個字符(因爲此時光標在末尾所以只能讀出空格)
''
>>> f.read(5)  
''
>>> f.tell()    //顯示文件輸入光標的位置
14 
>>> f.seek(3,0)  //從文件的開頭偏移3個字節
3  
>>> f.tell()   //顯示當前輸入籤的位置
3
>>> f.close()
>>> 
>>> f=open('f:\\record.txt')
>>> f.seek(0,0) //從文件的開頭偏移0個字節
0 
>>> lines=list(f)
>>> for each_line in lines:
	print(each_line)

	
我好餓呀呀呀

後開始發動了回覆

愛護和對方拉黑後

愛的哈盧胡話

好阿綱愛是個哈哈哈功夫還是
>>> f.close()
>>> 
  1. 文件的寫入
    f=open(‘E:\test.txt’,‘w’) f=open(‘E:\test.txt’,‘w’)
    f.write(‘我愛工作’)
    f.close()
    備註:“文件“內容比較重要需要再看視頻鞏固學習
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章