python基礎之函數式編程、匿名函數、內置函數

一 函數式編程

  1. 不修改外部狀態。
  2. 模仿數學裏得函數進行編程。
  3. 用函數編程寫出得代碼至關精簡。
  4. 可讀性比較差。

例子:html

y=2*x+1

x=1
def test(x):
	return 2*x+1
test(x)

一 匿名函數

  • 匿名函數就是不須要顯式的指定函數。
  • lambda的主體是一個表達式,而不是一個代碼塊。僅僅能在lamba表達式中封裝有限的邏輯進去。

注:匿名函數引用計數爲0,lambda常常和內置函數一塊兒使用python

  lambda/filter/map/reduce這些都是函數式編程的風格。express

語法:
lambda函數的語法只包含一個語句,以下:編程

lambda [arg1 [,arg2,.....argn]]:expression

 

先來個簡單得:python3.x

#這段代碼
def calc(n):
    return n**n
print(calc(10))

#換成匿名函數
calc = lambda n:n**n
print(calc(10))

 換個高級點得:app

salaries={
    'egon':3000,
    'alex':100000000,
    'wupeiqi':10000,
    'yuanhao':250
}

def get_value(k):
    return salaries[k]

#換成匿名函數:
lambda k:salaries[k]
f=lambda k:salaries[k] #匿名函數也能夠賦值一個名字,可是這便違反了匿名的初衷
print(f)
print(f('egon'))

print(max(salaries))
print(max(salaries,key=get_value))
print(max(salaries,key=lambda k:salaries[k]))
print(min(salaries,key=lambda k:salaries[k]))

二 內置函數

 

官方文檔,內置參數詳解:ssh

https://docs.python.org/3/library/functions.html?highlight=built#asciiide

數據類型內置函數,又稱爲工廠函數。函數式編程

 

函數是個具體的對象,誰來調用均可以用。方法須要綁定到具體對象。函數

l1=[]
l1.append('aaaa')

def test(x,item):
     x.append(item)
test(b,'bbbbb')
函數例子

 

內置函數使用示例:

一、abs絕對值

print(abs(-1))
print(abs(0))

執行結果:

1
0

二、all全部的都爲真,它才爲真

print(all(' '))  #注意all(' ')和all('')的區別,一個是空字符串,一個是空  
print(all(''))  #若是可迭代對象是空,就返回True。
print(all((1,' ',2)))
print(all((1,'',2)))
print(all((1,' ',2,None)))
print(all(i for i in range(1,10)))

執行結果:

True
True
True
False
False
True

三、any集合中的元素有一個爲真的時候爲真,特別的,若爲空串返回爲False

print(any([]))
print(any([0,'',None,{},1]))

執行結果:

False
True

四、bin把十進制轉成二進制

print(bin(3))

執行結果:

0b11

五、bool布爾值 空,None,0的布爾值爲False

print(bool(0))
print(bool(None))
print(bool(''))
print(bool([]))

執行結果:

False
False
False
False

六、bytes把字符串轉成字節

ps1:

name='你好'
print(bytes(name,encoding='utf-8'))
print(bytes(name,encoding='utf-8').decode('utf-8'))

執行結果:

b'\xe4\xbd\xa0\xe5\xa5\xbd'
你好

ps2:

name='你好'
print(bytes(name,encoding='gbk'))
print(bytes(name,encoding='gbk').decode('gbk'))

執行結果:

b'\xc4\xe3\xba\xc3'
你好

ps3: #ascll不能編碼中文,會報錯

name='你好'
print(bytes(name,encoding='ascii')) #ascii不能編碼中文,會報錯

執行結果:

Traceback (most recent call last):
  File "C:/Users/Administrator/PycharmProjects/untitled/day25/test.py", line 21, in <module>
    print(bytes(name,encoding='ascii')) #ascii不能編碼中文,會報錯
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

七、ASCII碼對應的編碼:

ps1:

print(chr(66))   #ascll 碼對應的編碼

執行結果:

B

ps2:

print(ord("B"))   #ascll 碼對應的編碼

執行結果:

66

八、數據類型:

int #整型

num=1 #num=int(1)
print(type(num)) #查看num的類型
print(isinstance(num,int)) #判斷num是否爲int類型

執行結果:

<class 'int'>
True
print(num is 1) #is 是身份運算,根據id去判斷身份

執行結果:

True

其餘數字類型:

float #浮點
bool #布爾
complex #複數

str #字符串

x='money' #x=str('money')
print(str(1))
print(str({'a':1}))

執行結果:

1
{'a': 1}

list #列表

x=[]
x=list(i for i in range(10))
print(x)

執行結果:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

tuple #元組
dict #字典

d={'a':1}
d=dict(x=1,y=2,z=3)
print(d)

執行結果:

{'x': 1, 'y': 2, 'z': 3}

set #集合

s={1,2,3,4,4}
print(s)
s.add(5)
print(s)

執行結果:

{1, 2, 3, 4}
{1, 2, 3, 4, 5}

frozenset #不可變集合

f=frozenset({1,2,3,4})
print(type(f))

執行結果:

<class 'frozenset'>

complex #複數

x=complex(1-2j)
print(x.real)
print(x.imag)

執行結果:

1.0
-2.0
x=1-2j
print(x.real)
print(x.imag)

執行結果:

1.0
-2.0

九、dir顯示函數內置屬性和方法:

print(dir(dict))  #打印內置屬性和方法

執行結果:

['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', 

'__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', 

'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', 

'__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

 

l=[]
print(dir(l))

執行結果:

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', 

'__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', 

'__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', 

'__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 

'insert', 'pop', 'remove', 'reverse', 'sort']

十、help 查看函數用法的說細信息

print(help(sum))

執行結果:

Help on built-in function sum in module builtins:

sum(iterable, start=0, /)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers
    
    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.

None

十一、divmod 取商得餘數,用於作分頁顯示功能

print(divmod(10,3)) #取商得餘數,用於作分頁顯示

執行結果:

(3, 1)

十二、enumerate返回一個可枚舉的對象,該對象的next()方法將返回一個tuple

for i in enumerate(['a','b','c','d']):
    print(i)
for i in enumerate({'x':1,'y':2}):
    print(i)

執行結果:

(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
(0, 'x')
(1, 'y')

1三、hash 可hash的數據類型即不可變數據類型,不可hash的數據類型便可變數據類型

print(hash('123abc'))
print(hash('123abcd'))
name='alex'
print(hash(name))
print('--->before',hash(name))
name='sb'
print('--->after',hash(name))

執行結果:

1142581611408458944
5571539217676805375
2895136519908427636
--->before 2895136519908427636
--->after -2600704963542853119

1四、bin、hex、oct進制轉換

print(bin(10))   #10進制->2進制
print(hex(12))   #10進制->16進制
print(oct(12))   #10進制->8進制

1五、id 返回對象的惟一標識id(object)

print(id('abc'))
a=1
b=2
print(id(a))
print(id(b))
x='a'
y='b'
print(id(x))
print(id(y))
print(x is y)

執行結果:

31023032
1589421152
1589421184
30945832
30931800
False

1六、max和min 最大值和最小值

print(max(1,2,3,4,10,3))
print(min(1,2,3,4,10,3))

執行結果:

10
1

1七、zip拉鍊,將對象逐一配對

l1=[1,2,3,4]
s='hel'
for i in zip(l1,s):
    print(i)
print(max((1,'a'),(1,'b')))

salaries={
    'egon':3000,
    'alex':100000000,
    'wupeiqi':10000,
    'yuanhao':250
}
print(salaries.keys(),salaries.values())
z=zip(salaries.values(),salaries.keys())
print(z)
for i in z:
    print(i)

執行結果:

(1, 'h')
(2, 'e')
(3, 'l')
(1, 'b')
dict_keys(['egon', 'alex', 'wupeiqi', 'yuanhao']) dict_values([3000, 100000000, 10000, 250])
<zip object at 0x00000000021BCF88>
(3000, 'egon')
(100000000, 'alex')
(10000, 'wupeiqi')
(250, 'yuanhao')

1八、sorted排序

l={3,4,1,0,9,10}
print(sorted(l)) #返回值是列表,默認是升序
print(sorted(l,reverse=True)) #降序排列
s='hello abc'
print(sorted(s))

salaries={
    'egon':3000,
    'alex':100000000,
    'wupeiqi':10000,
    'yuanhao':250
}
print(sorted(salaries)) #默認是按照字典salaries的key去排序的
print(sorted(salaries,key=lambda x:salaries[x]))
print(sorted(salaries,reverse=True,key=lambda x:salaries[x]))

執行結果:

[0, 1, 3, 4, 9, 10]
[10, 9, 4, 3, 1, 0]
[' ', 'a', 'b', 'c', 'e', 'h', 'l', 'l', 'o']

['alex', 'egon', 'wupeiqi', 'yuanhao']
['yuanhao', 'egon', 'wupeiqi', 'alex']
['alex', 'wupeiqi', 'egon', 'yuanhao']

排序且修改:

l=[3,2,0,10]
l=sorted(l)
print(l)

執行結果:

[0, 2, 3, 10]

1九、map映射,map(function,iterable,...)遍歷每一個元素,執行function操做

l=[1,2,3,7,5]
x={i**2 for i in l}
print(x)
iterm=2
m=map(lambda item:item**2,l)
print(m)
for i in m:
    print(i)
print(list(m))

name_1=['alex','yuanhao','wupeiqi']
m=map(lambda name:name+'SB',name_1)
print(list(m))

執行結果:

{1, 4, 9, 49, 25}
<map object at 0x00000000028099B0>
1
4
9
49
25
[]
['alexSB', 'yuanhaoSB', 'wupeiqiSB']

20、reduce 合併操做,從第一個開始是前兩個參數,而後是前兩個的結果與第三個合併進行處理,以此類推。

reduce(function,iterable[,initializer]) 

from functools import reduce #合併
l=list(range(100))
print(l)
print(reduce(lambda x,y:x+y,l,100))
i=iter(l)
# 100 next(i) --->100,0----->x,y-x+y-->100
# 100 next(i)---->100,1----->x,y--x+y-->101
# 101 next(i)----->101,2

執行結果:

[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, 32, 33, 34, 

35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 

68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
5050

2一、filter過濾

name_l=[
    {'name':'egon','age':18},
    {'name':'alex','age':1000},
    {'name':'wupeiqi','age':9000},
    {'name':'yuanhao','age':10000},
]

f=filter(lambda d:d['age'] > 100,name_l)
print(f)
for i in f:
    print(i)

執行結果:

<filter object at 0x00000000027A9BA8>
{'name': 'alex', 'age': 1000}
{'name': 'wupeiqi', 'age': 9000}
{'name': 'yuanhao', 'age': 10000}

2二、pow 幾的幾回方

print(pow(3,2,2)) #3**3%2 3的3次方,取餘
print(pow(3,3)) #3**3 幾的幾回方,至關於3的3次方

執行結果:

1
27

2三、reversed 反轉

print(list(reversed([1,5,3,9])))

執行結果:

[9, 3, 5, 1]

2四、round  四捨五入

當數字n是兩個相鄰整數的中間值(例如 1.五、2.五、3.5和4.5)時,round函數將返回與其最爲接近的偶數。
例如,round(2.5)的結果是2,而round(3.5)的結果是4。
decimal的默認context是"四捨六入五留雙"。(只針對python3.x)

print(round(2.6))
print(round(2.5))
print(round(3.4))
print(round(3.5))

執行結果:

3
2
3
4

2五、slice 切片

l=[1,2,3,4,5,6]
print(l[2:5:2])
s=slice(2,5,2)
print(l[s])

執行結果:

[3, 5]
[3, 5]

2六、vars跟一個列表或多個字典

print(vars())
print(vars() is locals())

執行結果:

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 

0x000000000068A358>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 

'C:/Users/Administrator/PycharmProjects/untitled/day25/test.py', '__cached__': None}
True

2七、import模塊

一、先建立一個test.py文件
寫入內容以下:

def say_hi():
    print('你好啊egon')

二、再調用這個模塊

import test #寫入一個模塊,模塊就是一個py文件
test.say_hi()

執行結果:

你好啊egon

2八、__import__: 導入一個字符串類型模塊,就要用__import__

一、先建立一個test.py文件
寫入內容以下:

def say_hi():
    print('你好啊egon')

二、再調用這個模塊

module_name='test'
m=__import__(module_name)
m.say_hi()

執行結果:

你好啊egon

 

其餘內容,在面向對象裏講:

classmethod
staticmethod
property

delattr
hasattr
getattr
setattr

issubclass
super
其餘內置函數

 

練習題:

做業1、

一、用map來處理字符串列表啊,把列表中全部人都變成sb,比方alex_sb

  name=['alex','wupeiqi','yuanhao']

m=map(lambda name:name+'_sb',name)
print(list(m))

二、用map來處理下述l,而後用list獲得一個新的列表,列表中每一個人的名字都是sb結尾

  l=[{'name':'alex'},{'name':'y'}]

print(list(map(lambda i:{'name':i['name']+"sb"},l)))

做業二:

一、用filter來處理,獲得股票價格大於20的股票名字

shares={
'IBM':36.6,
'Lenovo':23.2,
'oldboy':21.2,
'ocean':10.2,
}

res=filter(lambda x:shares[x]>20,shares)
print(list(res))
或者
for i in res:
    print(i)

做業三:

以下,每一個小字典的name對應股票名字,shares對應多少股,price對應股票的價格

portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]

一、map來得出一個包含數字的迭代器,數字指的是:購買每支股票的總價格

res=map(lambda x:x['shares']*x['price'],portfolio)
print(list(res))
或者
for i in res:
    print(i)

二、基於1的結果,用reduce來計算,購買這些股票總共花了多少錢

l1=[]
res=map(lambda x:x['shares']*x['price'],portfolio)
print(list(res))
或者
for i in res:
    l1.append(i)

res=reduce(lambda x,y:x+y,l1)
print(res)

三、用filter過濾出,單價大於100的股票有哪些

res=filter(lambda x:x["price"]>100,portfolio)
for i in res:
    print(i)
相關文章
相關標籤/搜索