python 基礎函數

來源:互聯網
上載者:User

標籤:***   cto   可變參數   hex   func   lis   number   numbers   可變參   

1、函數定義: def fun():

       ***

       return

Note:函數名其實就是指向一個函數對象的引用,完全可以把函數名賦給一個變數,相當於給這個函數起了一個“別名”

2、函數參數:預設參數:def power(x, n=2):  可調用:power(x) 定義預設參數要牢記一點:預設參數必須指向不變對象     

           可變參數:可變參數允許你傳入0個或任意個參數 def calc(*numbers):calc(1, 3, 5, 7) 或 nums=[1, 3, 5, 7] calc(*nums)
              關鍵字參數:關鍵字參數允許你傳入0個或任意個含參數名的參數,這些關鍵字參數在函數內部自動組一個dict。def person(name, age, **kw): person(‘Adam‘, 45, gender=‘M‘, job=‘Engineer‘)
或 extra = {‘city‘: ‘Beijing‘, ‘job‘: ‘Engineer‘} person(‘Jack‘, 24, **extra) 
             命名關鍵字參數:def person(name, age, *, city, job): city與job如果是非預設參數則必須傳入參數名

NOTE:參數定義的順序必須是:必選參數、預設參數、可變參數、命名關鍵字參數和關鍵字參數。

3、高階函數 #函數參數可以傳入函數

4、常用函數

   help 函數

   通過help() 查看函數的協助。如:help(abs)

   int() 可以把其他資料類型轉換為整數。類似的還有:float() str() bool() hex()

   isinstance(objet, classinfo) 如 isinstance(1,int) isinstance(‘abc‘, Interable)#判斷是否可迭代(from collectins import Interable)

   enumerate #將lis變成索引-元素對  for i, value in enumerate([‘a‘,‘b‘,‘c‘])

                                                        print (i, value)

 map():函數接收兩個參數,一個是函數,一個是Iterablemap將傳入的函數依次作用到序列的每個元素,並把結果作為新的Iterator返回

      list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
   reduce():把一個函數作用在一個序列上,把結果繼續和序列的下一個元素做累積計算(from functools import reduce)

      reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)

   lambda匿名函數:允許使用者快速定義單行函數 log2=lambda x:log(x)/log(2)

  filter():函數用於過濾序列,接收一個函數和一個序列,然後根據傳回值是True還是False決定保留還是丟棄該元素.

    list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
   sorted():sorted([36, 5, -12, 9, -21], key=abs)

python 基礎函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.