- 課上代碼
>>> count = 5
>>> def MyFun():
count = 10
print(10)
>>> MyFun()
10
>>> print(count)
5
>>> def MyFun():
global count
count = 10
print(10)
>>> MyFun()
10
>>> print(count)
10
>>> def fun1():
print('fun1()正在被調(diào)用...')
def fun2():
print('fun2()正在被調(diào)用...')
fun2()
>>> fun1()
fun1()正在被調(diào)用...
fun2()正在被調(diào)用...
>>> def FunX(x):
def FunY(y):
return x * y
return FunY
>>> i = FunX(8)
>>> i
<function FunX.<locals>.FunY at 0x0000017712511620>
>>> type(i)
<class 'function'>
>>> i(5)
40
>>> FunX(8)(5)
40
>>> FunY(5)
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
FunY(5)
NameError: name 'FunY' is not defined
>>> def Fun1():
x = 5
def Fun2():
x *= x
return x
return Fun2()
>>> Fun1()
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
Fun1()
File "<pyshell#40>", line 6, in Fun1
return Fun2()
File "<pyshell#40>", line 4, in Fun2
x *= x
UnboundLocalError: local variable 'x' referenced before assignment
>>> Fun2()
Traceback (most recent call last):
File "<pyshell#42>", line 1, in <module>
Fun2()
NameError: name 'Fun2' is not defined
#修改方法
>>> def Fun1():
x = [5]
def Fun2():
x[0] *= x[0]
return x
return Fun2()
>>> Fun1()
[25]
>>> def Fun1():
x = 5
def Fun2():
nonlocal x #強制聲明為不是一個局部變量
x *= x
return x
return Fun2()
>>> Fun1()
25
>>> def ds(x):
return 2 * x + 1
>>> ds(5)
11
'''python寫一些執(zhí)行腳本時,
使用lambda就可以省下定義函數(shù)過程舞蔽,
比如說我們只是需要寫個簡單的腳本來管理服務(wù)器時間荣病,
我們就不需要專門定義一個函數(shù)然后再寫調(diào)用,
使用lambda就可以使得代碼更加精簡'''
'''對于一些比較抽象并且整個程序執(zhí)行下來只需要調(diào)用一兩次的函數(shù)渗柿,
有時候給函數(shù)起個名字也是比較頭疼的問題个盆,
使用lambda就不需要考慮命名的問題了'''
'''簡化代碼的可讀性脖岛,
由于普通的函數(shù)閱讀經(jīng)常要跳到開頭def定義部分,
使用lambda函數(shù)可以省去這樣的步驟'''
>>> lambda x : 2 * x + 1
<function <lambda> at 0x101f62e18>
>>> g = lambda x : 2 * x + 1
>>> g(5)
11
>>> def add(x, y):
return x + y
>>> add(3, 4)
7
>>> lambda x, y : x + y
<function <lambda> at 0x1120d27b8>
>>> g = lambda x, y : x + y
>>> g(3, 4)
7
>>> help(filter)
Help on class filter in module builtins:
class filter(object)
| filter(function or None, iterable) --> filter object
|
| Return an iterator yielding those items of iterable for which function(item)
| is true. If function is None, return the items that are true.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
>>> filter(None, [1, 0, False, True])
<filter object at 0x1120c8ef0>
#filter()是過濾的bif
>>> list(filter(None, [1, 0, False, True]))
[1, True]
>>> def odd(x):
return x % 2
#這個返回奇數(shù)的方式很巧妙
>>> 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]
>>> list(map(lambda x : x * 2, range(10)))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
#map()是映射的bif
二. 測試題
- 請問如何訪問funIn()呢颊亮?
>>> def funOut():
def funIn():
print("Bingo! You got me!")
return funIn()
>>> funOut()
Bingo! You got me!
- 請問如何訪問funIn()呢柴梆?
>>> def funOut():
def funIn():
print("Bingo! You got me!")
return funIn
>>> funOut()()
Bingo! You got me!
#或者可以用
>>> go = funOut()
>>> go()
Bingo! You got me!
- 以下是閉包的一個例子,目測會打印什么內(nèi)容终惑?
def funX():
x = 5
def funY():
nonlocal x
x += 1
return x
return funY
a = funX()
print(a())
print(a())
print(a())
>>>
=================== RESTART: C:\Users\xin\Desktop\game.py ===================
6
7
8
- 請將下面的匿名函數(shù)轉(zhuǎn)變?yōu)槠胀ǖ暮瘮?shù)
>>> lambda x: x if x % 2 else None
>>> def function(x):
if x % 2 == 1:
return x
else:
return None
- 利用filter()和lambda表達式快速求出100以內(nèi)所有3的倍數(shù)
>>> list(filter(lambda n: not(n % 3), range(1, 100)))
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
- zip()會將兩數(shù)以元組的形式綁定在一起绍在,例如:
>>> list(zip([1, 3, 5, 7, 9], [2, 4, 6, 8, 10]))
[(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
如果希望打包的形式是靈活多變的列表而不是元組,用map()和lambda表達式來解決
>>> list(map(lambda x, y: [x, y], [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]))
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
#直接把數(shù)據(jù)懟上去就行了
>>> def even(x):
return x % 2 == 0
>>> def odd(x):
return x % 2
>>> temp = range(1, 11)
>>> list(temp)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> show_odd = filter(odd, temp)
>>> show_even = filter(even, temp)
>>> list(show_odd)
[1, 3, 5, 7, 9]
>>> list(show_even)
[2, 4, 6, 8, 10]
>>> map(lambda x, y: [x, y], show_odd, show_even)
<map object at 0x112117198>
>>> list(map(lambda x, y: [x, y], show_odd, show_even))
[]
#這樣求出的兩個數(shù)組然后懟上去反而不行雹有,暫不知原因偿渡,待詳查
- 目測一下表達式會打印什么?
>>> def make_repeat(n):
return lambda s: s * n
>>> double = make_repeat(2)
>>> print(double(8))
>>> print(double('FishC'))
#16
#FishCFishC
三. 動動手
- 統(tǒng)計長字符串中各個字符出現(xiàn)的次數(shù)
total_library = open('E:\\string1.txt', 'r')
total_library = total_library.read()
character_library = []
#check_character_number = 0
#L = []
for each in total_library:
if each not in character_library:
if each == '\n':
print('\\n', total_library.count(each))
else:
print(each, total_library.count(each))
character_library.append(each)
print(character_library)
'''length = len(character_library)
while length >= 1:
check_character = character_library[length - 1]
length = length - 1
for i in total_library:
if i == check_character:
check_character_number += 1
return check_character_number
print(check_character_number)
L.append(check_character_number)
L.reverse()
print(L)
print(character_library)'''
#注釋處是我寫的代碼霸奕,目前還在debug
- 找出字符串中的密碼溜宽,密碼的埋藏點符合以下規(guī)律:
(1) 每位密碼為單個小寫字母
(2) 每位密碼的左右兩邊均有且只有三個大寫字母
#個人代碼
total_library = open('E:\\string2.txt', 'r')
total_library = total_library.read()
length = len(total_library)
L = []
for i in range(3, length - 2):
if 97 <= ord(total_library[i]) <= 122 and 65 <= ord(total_library[i + 1]) <= 90 and 65 <= ord(total_library[i - 1]) <= 90 and 65 <= ord(total_library[i + 2]) <= 90 and 65 <= ord(total_library[i - 2]) <= 90 and 65 <= ord(total_library[i + 3]) <= 90 and 65 <= ord(total_library[i - 3]) <= 90 and (ord(total_library[i + 4]) > 90 or ord(total_library[i + 4]) < 65) and (ord(total_library[i - 4]) > 90 or ord(total_library[i - 4]) < 65): #(97 <= ord(total_library[i + 4]) <= 122 or 97 <= ord(total_library[i - 4]) <= 122 or 48 <= ord(total_library[i + 4]) <= 57 or 48 <= ord(total_library[i - 4]) <= 57):
L.append(total_library[i])
print(L)
參考代碼
str1 = open('E:\\string2.txt', 'r')
str1 = str1.read()
countA = 0 #統(tǒng)計前邊的大寫字母
countB = 0 #統(tǒng)計小寫字母
countC = 0 #統(tǒng)計后邊的大寫字母
length = len(str1)
for i in range(length):
if str1[i] == '\n':
continue
if str1[i].isupper(): #如果str1[i]是大寫字母
if countB: #統(tǒng)計后邊的大寫字母
countC += 1
else: #如果未出現(xiàn)小寫字母
countC = 0 #清空后邊大寫字母的統(tǒng)計
countA += 1 #統(tǒng)計前邊的大寫字母
if str1[i].islower(): #如果str1[i]是小寫字母
if countA != 3: #如果小寫字母前邊不是三個大寫字母(不符合條件)
countA = 0
countB = 0
countC = 0 #清空所有記錄,重新統(tǒng)計
else: #如果小寫字母前邊是三個大寫字母(符合條件)
if countB: #如果已經(jīng)存在小寫字母
countA = 0
countB = 0
countC = 0 #清空所有記錄,重新統(tǒng)計(出現(xiàn)兩個小寫字母)
else: #如果該小寫字母是唯一的
countB = 1
countC = 0
target = i #countB記錄出現(xiàn)小寫字母,準備開始統(tǒng)計countC
if countA == 3 and countC == 3: #如果前邊和后邊都是三個大寫字母
if i + 1 != length and str1[i + 1].isupper(): #如果后邊第四個字母也是大寫字母(不符合條件)
countB = 0
countC = 0 #清空B和C哮独,重新統(tǒng)計
else: #如果后邊僅有三個大寫字母(符合所有條件)
print(str1[target], end = '')
countA = 3
countB = 0
countC = 0 #打印結(jié)果戳粒,并清空所有記錄,進入下一輪統(tǒng)計
#what the f**k????????