Python基礎學習之常見的內建函數整理,python基礎建函數

來源:互聯網
上載者:User

Python基礎學習之常見的內建函數整理,python基礎建函數

 前言

Python針對眾多的類型,提供了眾多的內建函數來處理,這些內建函數功用在於其往往可對多種類型對象進行類似的操作,即多種類型對象的共有的操作,下面話不多說了,來一看看詳細的介紹吧。

map()

map()函數接受兩個參數,一個是函數,一個是可迭代對象(Iterable),map將傳入的函數依次作用到可迭代對象的每一個元素,並把結果作為迭代器(Iterator)返回。

舉例說明,有一個函數f(x)=x^2 ,要把這個函數作用到一個list[1,2,3,4,5,6,7,8,9]上:

運用簡單的迴圈可以實現:

>>> def f(x):...  return x * x...L = []for n in [1, 2, 3, 4, 5, 6, 7, 8, 9]: L.append(f(n))print(L)

運用高階函數map()

>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])>>> list(r)[1, 4, 9, 16, 25, 36, 49, 64, 81]

結果r是一個迭代器,迭代器是惰性序列,通過list()函數讓它把整個序列都計算出來並返回一個list。

如果要把這個list所有數字轉為字串利用map()就簡單了:

>>> list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))['1', '2', '3', '4', '5', '6', '7', '8', '9']

小練習:利用map()函數,把使用者輸入的不規範的英文名字變為首字母大寫其他小寫規範名字。輸入['adam', 'LISA', 'barT'],輸出['Adam', 'Lisa', 'Bart']

def normalize(name):  return name.capitalize() l1=["adam","LISA","barT"] l2=list(map(normalize,l1)) print(l2)

reduce()

reduce()函數也是接受兩個參數,一個是函數,一個是可迭代對象,reduce將傳入的函數作用到可迭代對象的每個元素的結果做累計計算。然後將最終結果返回。

效果就是:reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

舉例說明,將序列[1,2,3,4,5]變換成整數12345:

>>> from functools import reduce>>> def fn(x, y):...  return x * 10 + y...>>> reduce(fn, [1, 2, 3, 4, 5])12345

小練習:編寫一個prod()函數,可以接受一個list並利用reduce求積:

from functools import reducedef pro (x,y):  return x * y def prod(L):  return reduce(pro,L) print(prod([1,3,5,7]))

map()reduce()綜合練習:編寫str2float函數,把字串'123.456'轉換成浮點型123.456

CHAR_TO_FLOAT = { '0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9': 9, '.': -1}def str2float(s): nums = map(lambda ch:CHAR_TO_FLOAT[ch],s) point = 0 def to_float(f,n):   nonlocal point   if n==-1:    point =1    return f   if point ==0:    return f*10+n   else:    point =point *10    return f + n/point return reduce(to_float,nums,0)#第三個參數0是初始值,對應to_float中f

filter()

filter()函數用於過濾序列,filter()也接受一個函數和一個序列,filter()把傳入的函數依次作用於每個元素,然後根據傳回值是True還是False決定保留還是丟棄該元素。

舉例說明,刪除list中的偶數:

def is_odd(n): return n % 2 == 1list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))# 結果: [1, 5, 9, 15]

小練習:用filter()求素數

計算素數的一個方法是埃氏篩法,它的演算法理解起來非常簡單:

首先,列出從2開始的所有自然數,構造一個序列:

2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

取序列的第一個數2,它一定是素數,然後用2把序列的2的倍數篩掉:

3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

取新序列的第一個數3,它一定是素數,然後用3把序列的3的倍數篩掉:

5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

取新序列的第一個數5,然後用5把序列的5的倍數篩掉:

7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

不斷篩下去,就可以得到所有的素數。

用Python實現這個演算法,先構造一個從3開始的期數數列:

def _odd_iter(): n = 1 while True:  n = n + 2  yield n#這是一個產生器,並且是一個無線序列

定義一個篩選函數:

def _not_divisible(n): return lambda x: x % n > 0

定義一個產生器不斷返回下一個素數:

def primes(): yield 2 it = _odd_iter() # 初始序列 while True:  n = next(it) # 返回序列的第一個數  yield n  it = filter(_not_divisible(n), it) # 構造新序列

列印100以內素數:

for n in primes(): if n < 100:  print(n) else:  break

sorted()

python內建的sorted()函數可以對list進行排序:

>>> sorted([36, 5, -12, 9, -21])[-21, -12, 5, 9, 36]

sorted()函數也是一個高階函數,還可以接受一個key函數來實現自訂排序:

>>> sorted([36, 5, -12, 9, -21], key=abs)[5, 9, -12, -21, 36]

key指定的函數將作用於list的每一個元素上,並根據key函數返回的結果進行排序.

預設情況下,對字串排序,是按照ASCII的大小比較的,由於'Z' < 'a',結果,大寫字母Z會排在小寫字母a的前面。如果想忽略大小寫可都轉換成小寫來比較:

>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)['about', 'bob', 'Credit', 'Zoo']

要進行反向排序,不必改動key函數,可以傳入第三個參數reverse=True

>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)['Zoo', 'Credit', 'bob', 'about']

小練習:假設我們用一組tuple表示學生名字和成績:L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] 。用sorted()對上述列表分別按c成績從高到低排序:

L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]def by_score(t): for i in t:   return t[1]L2=sorted(L,key= by_score)print(L2)

運用匿名函數更簡潔:

L2=sorted(L,key=lambda t:t[1])print(L2)

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的協助,如果有疑問大家可以留言交流,謝謝大家對幫客之家的支援。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.