python常用函式的用法 python常用函式

2021-10-10 19:16:17 字數 4354 閱讀 9206

目錄

1、lambda

2、map

3、屬性函式-property

4、@staticmethod

正文lambda()函式

舉個例子如下:func=lambda x:x+1

print(func(1))

#2print(func(2))

#3#以上lambda等同於以下函式def func(x):

return(x+1)

可以這樣認為,lambda作為乙個表示式,定義了乙個匿名函式,上例的**x為入口引數,x+1為函式體。在這裡lambda簡化了函式定義的書寫形式。是**更為簡潔,但是使用函式的定義方式更為直觀,易理解。

python中,也有幾個定義好的全域性函式方便使用的,filter, map, reduce。from functools import reduce

foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]

print (list(filter(lambda x: x % 3 == 0, foo)))

#[18, 9, 24, 12, 27]

print (list(map(lambda x: x * 2 + 10, foo)))

#[14, 46, 28, 54, 44, 58, 26, 34, 64]

print (reduce(lambda x, y: x + y, foo))

#139

上面例子中的map的作用,非常簡單清晰。但是,python是否非要使用lambda才能做到這樣的簡潔程度呢?在物件遍歷處理方面,其實python的for..in..if語法已經很強大,並且在易讀上勝過了lambda。

比如上面map的例子,可以寫成:print ([x * 2 + 10 for x in foo]) 非常的簡潔,易懂。

filter的例子可以寫成:print ([x for x in foo if x % 3 == 0]) 同樣也是比lambda的方式更容易理解。

map()函式

map()是 python 內建的高階函式,它接收乙個函式 f 和乙個 list,並通過把函式 f 依次作用在 list 的每個元素上,得到乙個新的 list 並返回。

例如,對於list [1, 2, 3, 4, 5, 6, 7, 8, 9]

如果希望把list的每個元素都作平方,就可以用map()函式:

因此,我們只需要傳入函式f(x)=x*x,就可以利用map()函式完成這個計算:def f(x):

return x*x

print map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])

輸出結果:

[1, 4, 9, 10, 25, 36, 49, 64, 81]

注意:map()函式不改變原有的 list,而是返回乙個新的 list。

利用map()函式,可以把乙個 list 轉換為另乙個 list,只需要傳入轉換函式。

由於list包含的元素可以是任何型別,因此,map() 不僅僅可以處理只包含數值的 list,事實上它可以處理包含任意型別的 list,只要傳入的函式f可以處理這種資料型別。

任務假設使用者輸入的英文名字不規範,沒有按照首字母大寫,後續字母小寫的規則,請利用map()函式,把乙個list(包含若干不規範的英文名字)變成乙個包含規範英文名字的list:

輸入:['adam', 'lisa', 'bart']

輸出:['adam', 'lisa', 'bart']def format_name(s):

s1=s[0:1].upper()+s[1:].lower();

return s1;

print map(format_name, ['adam', 'lisa', 'bart'])

map()函式是python內建的高階函式,對傳入的list的每乙個元素進行對映,返回乙個新的對映之後的list

屬性函式-property

python中有乙個被稱為屬性函式(property)的小概念,它可以做一些有用的事情,比如能做以下幾點:將類方法轉換為唯讀屬性

重新實現乙個屬性的setter和getter方法

使用屬性函式的最簡單的方法之一是將它作為乙個方法的裝飾器來使用。這可以讓你將乙個類方法轉變成乙個類屬性。當我需要做某些值的合併時,我發現這很有用。其他想要獲取它作為方法使用的人,發現在寫轉換函式時它很有用。讓我們來看乙個簡單的例子:class person(object):

def __init__(self, first_name, last_name):

"""constructor"""

self.first_name = first_name

self.last_name = last_name

@property

def full_name(self):

return the full name

return "%s %s" % (self.first_name, self.last_name)

在上面的**中,我們建立了兩個類屬性:self.first_name和self.last_name。接下來,我們建立了乙個full_name方法,它有乙個@property裝飾器。這使我們能夠在python直譯器會話中有如下的互動:

>>> person = person("mike", "driscoll")

>>> person.full_name

'mike driscoll'

>>> person.first_name

'mike'

正如你所看到的,因為我們將方法變成了屬性,我們可以使用正常的點符號訪問它。但是,如果我們試圖將該屬性設為其他值,我們會引發乙個attributeerror錯誤。改變full_name屬性的唯一方法是間接這樣做:>>> person.first_name = "dan"

>>> person.full_name

'dan driscoll'

staticmethod 靜態方法

python中的staticmethod 主要是方便將外部函式整合到類體中,美化**結構,重點在不需要類例項化的情況下呼叫方法

如果你去掉staticmethod,在方法中加self也可以通過例項化訪問方法也是可以整合**

1)先看看不使用staticmethod的**如何寫的ind='on'

def checkind():

return (ind == 'on')

class kls(object):

def __init__(self,data):

self.data = data

def do_reset(self):

if checkind():

print ('reset done for:',self.data)

def set_reset(self):

if checkind():

# self.db='new db connection'

print ('db connection mode for:',self.data)

ik1 = kls(12)

print (ik1.do_reset())

print (ik1.set_reset())

結果reset done for: 12

none

db connection mode for: 12

none

2)再看看使用staticmethod的**,用staticmethod包裝的方法可以內部呼叫,也可以通過類訪問或類例項化訪問ind='on'

class kls(object):

def __init__(self,data):

self.data = data

@staticmethod

def checkind():

return (ind == 'on')

def do_reset(self):

if self.checkind():

print ('reset done for:',self.data)

def set_reset(self):

if self.checkind():

# self.db='new db connection'

print ('db connection mode for:',self.data)

ik1 = kls(12)

print (ik1.do_reset())

print (ik1.set_reset())

print (ik1.checkind())

print (kls.checkind())

結果reset done for: 12

none

db connection mode for: 12

none

true

true

py 內建函式用法分析

type type 函式本身是乙個類,有兩種呼叫方式 class type object class type name,bases,dict class type object 傳入單個物件時,返回的是物件的型別,其作用跟object.class 方法一樣。但不建議用該函式檢測物件的型別,更推薦使...

python 常用函式用法

assert 斷言assert的語法其實有點像是fi 條件分支語句的 近親 assert這個關鍵字稱為 斷言 當這個關鍵字後邊的條件為false的時候,程式自動崩潰並丟擲assertionerror的異常 當在測試程式的時候就很好用,因為與其讓錯誤的條件導致程式今後莫名的崩潰,不如在錯誤條件出現的那...

python常用內建函式用法精要

用乙個 大致總結一下所有的內建函式用法,如下 函式功能簡要說明 abs x 返回數字x的絕對值或複數x的模 all iterable 如果對於可迭代物件中所有元素x都等價於true,則返回true。對於空的迭代物件也可返回true。any iterable 只要可迭代物件iterable中存在元素x...