成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

Python 基礎(chǔ)

Ashin / 2101人閱讀

摘要:基礎(chǔ)基礎(chǔ)函數(shù)定義一個函數(shù)要使用語句,依次寫出函數(shù)名括號括號中的參數(shù)和冒號,然后,在縮進塊中編寫函數(shù)體,函數(shù)的返回值用語句返回。用循環(huán)調(diào)用時,發(fā)現(xiàn)拿不到的語句的返回值。

Python 基礎(chǔ) 基礎(chǔ) 函數(shù)
定義一個函數(shù)要使用def語句,依次寫出函數(shù)名、括號、括號中的參數(shù)和冒號:,然后,在縮進塊中編寫函數(shù)體,函數(shù)的返回值用return語句返回。
def my_abs(x):
    if x >= 0:
        return x
    else:
        return -x
// my_abs(-9)  調(diào)用        
空函數(shù)

如果想定義一個什么事也不做的空函數(shù),可以用pass語句:

def nop():
    pass
// pass 作為占位符    

在其他語句里

if age >= 18:
    pass
參數(shù)檢查
調(diào)用函數(shù)時,如果參數(shù)個數(shù)不對,Python解釋器會自動檢查出來,并拋出TypeError
def my_abs(x):
    if not isinstance(x, (int, float)):
        raise TypeError("bad operand type")
    // 數(shù)據(jù)類型檢查可以用內(nèi)置函數(shù)isinstance()實現(xiàn):
    if x >= 0:
        return x
    else:
        return -x
返回多個值
import math

def move(x, y, step, angle=0):
    nx = x + step * math.cos(angle)
    ny = y - step * math.sin(angle)
    return nx, ny
    
默認參數(shù)
定義默認參數(shù)要牢記一點:默認參數(shù)必須指向不變對象!
def enroll(name, gender, age=6, city="shanghai"):
  print("gender:",gender)
  print("age:",age)
  print("city:",city)

enroll("shan","F")
enroll("shan","M",5,"beijing")
enroll("shan","F",age=6)

def add_end(L=None):
    if L is None:
        L = []
    L.append("END")
    return L
    
add_end()    
可變參數(shù)
def calc(numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum
    
calc([1, 2, 3]) //  調(diào)用的時候,需要先組裝出一個list或tuple
calc(1, 2, 3)
nums = [1, 2, 3]
calc(*nums)   // 定義可變參數(shù)和定義一個list或tuple參數(shù)相比,僅僅在參數(shù)前面加了一個*號

關(guān)鍵字參數(shù)

關(guān)鍵字參數(shù)允許你傳入0個或任意個含參數(shù)名的參數(shù),這些關(guān)鍵字參數(shù)在函數(shù)內(nèi)部自動組裝為一個dict
def person(name, age, **kw):
    print("name:", name, "age:", age, "other:", kw)
    
person("Bob", 35, city="Beijing")
person("Adam", 45, gender="M", job="Engineer")
extra = {"city": "Beijing", "job": "Engineer"}
person("Jack", 24, **extra)   // **extra表示把extra這個dict的所有key-value用關(guān)鍵字參數(shù)傳入到函數(shù)的**kw參數(shù)  
命名關(guān)鍵字參數(shù)
如果要限制關(guān)鍵字參數(shù)的名字,就可以用命名關(guān)鍵字參數(shù),例如,只接收city和job作為關(guān)鍵字參數(shù)
和關(guān)鍵字參數(shù)*kw不同,命名關(guān)鍵字參數(shù)需要一個特殊分隔符,*后面的參數(shù)被視為命名關(guān)鍵字參數(shù)。
def person(name, age, *, city, job):
    print(name, age, city, job)

person("Jack", 24, city="Beijing", job="Engineer")
# person("Jack", 24, "Beijing", "Engineer")   命名關(guān)鍵字參數(shù)必須傳入?yún)?shù)名,這和位置參數(shù)不同。如果沒有傳入?yún)?shù)名,調(diào)用將報錯

如果沒有可變參數(shù),就必須加一個作為特殊分隔符。如果缺少,Python解釋器將無法識別位置參數(shù)和命名關(guān)鍵字參數(shù):

def person(name, age, city, job):
    # 缺少 *,city和job被視為位置參數(shù)
    pass
參數(shù)組合
在Python中定義函數(shù),可以用必選參數(shù)、默認參數(shù)、可變參數(shù)、關(guān)鍵字參數(shù)和命名關(guān)鍵字參數(shù),這5種參數(shù)都可以組合使用。

參數(shù)定義的順序必須是:必選參數(shù)、默認參數(shù)、可變參數(shù)、命名關(guān)鍵字參數(shù)和關(guān)鍵字參數(shù)。

def f1(a, b, c=0, *args, **kw):
    print("a =", a, "b =", b, "c =", c, "args =", args, "kw =", kw)
def f2(a, b, c=0, *, d, **kw):
    print("a =", a, "b =", b, "c =", c, "d =", d, "kw =", kw)

在函數(shù)調(diào)用的時候,Python解釋器自動按照參數(shù)位置和參數(shù)名把對應(yīng)的參數(shù)傳進去。

>>> f1(1, 2)
a = 1 b = 2 c = 0 args = () kw = {}
>>> f1(1, 2, c=3)
a = 1 b = 2 c = 3 args = () kw = {}
>>> f1(1, 2, 3, "a", "b")
a = 1 b = 2 c = 3 args = ("a", "b") kw = {}
>>> f1(1, 2, 3, "a", "b", x=99)
a = 1 b = 2 c = 3 args = ("a", "b") kw = {"x": 99}
>>> f2(1, 2, d=99, ext=None)
a = 1 b = 2 c = 0 d = 99 kw = {"ext": None}

最神奇的是通過一個tuple和dict,你也可以調(diào)用上述函數(shù):

>>> args = (1, 2, 3, 4)
>>> kw = {"d": 99, "x": "#"}
>>> f1(*args, **kw)
a = 1 b = 2 c = 3 args = (4,) kw = {"d": 99, "x": "#"}
>>> args = (1, 2, 3)
>>> kw = {"d": 88, "x": "#"}
>>> f2(*args, **kw)
a = 1 b = 2 c = 3 d = 88 kw = {"x": "#"}
遞歸函數(shù)
在函數(shù)內(nèi)部,可以調(diào)用其他函數(shù)。如果一個函數(shù)在內(nèi)部調(diào)用自身本身,這個函數(shù)就是遞歸函數(shù)。

舉個例子,計算階乘n! = 1 x 2 x 3 x ... x n

def fact(n):
    if n==1:
        return 1
    return n * fact(n - 1)

使用遞歸函數(shù)需要注意防止棧溢出。在計算機中,函數(shù)調(diào)用是通過棧(stack)這種數(shù)據(jù)結(jié)構(gòu)實現(xiàn)的,每當進入一個函數(shù)調(diào)用,棧就會加一層棧幀,每當函數(shù)返回,棧就會減一層棧幀。由于棧的大小不是無限的,所以,遞歸調(diào)用的次數(shù)過多,會導(dǎo)致棧溢出。

可以試試fact(1000):

尾遞歸是指,在函數(shù)返回的時候,調(diào)用自身本身,并且,return語句不能包含表達式。這樣,編譯器或者解釋器就可以把尾遞歸做優(yōu)化,使遞歸本身無論調(diào)用多少次,都只占用一個棧幀,不會出現(xiàn)棧溢出的情況。

def fact(n):
    return fact_iter(n, 1)

def fact_iter(num, product):
    if num == 1:
        return product
    return fact_iter(num - 1, num * product)
    
切片

取前N個元素

 L = ["Michael", "Sarah", "Tracy", "Bob", "Jack"]
 for i in range(n):
     r.append(L[i])
  L[0:3] // 完成切片 
 L[-2:]  // 倒數(shù)第2個開始

L[0:3]表示,從索引0開始取,直到索引3為止,但不包括索引3。即索引0,1,2,正好是3個元素。
倒數(shù)第一個元素的索引是-1

L = list(range(100))
# >>> L [0, 1, 2, 3, ..., 99]

>>> L[:10] 前10個數(shù)
>>> L[-10:] 后10個數(shù):
>>> L[10:20] 前11-20個數(shù)
>>> L[:10:2]  前10個數(shù),每兩個取一個
>>> L[::5] 所有數(shù),每5個取一個:
>>> L[:] 所有的

字符串"xxx"也可以看成是一種list,每個元素就是一個字符。

>>> "ABCDEFG"[:3]
"ABC"
>>> "ABCDEFG"[::2]
"ACEG"

def trim(s):
  if (s[:1] == " "):
    return trim(s[1:])
  if (s[-1:] == " "):
    return trim(s[:-1])
  return s
迭代

如果給定一個list或tuple,通過for循環(huán)來遍歷這個list或tuple,這種遍歷我們稱為迭代(Iteration)

d = {"a": 1, "b": 2, "c": 3}
for key in d:
  print(key)

dict的存儲不是按照list的方式順序排列,所以,迭代出的結(jié)果順序很可能不一樣

for ch in "abcde"
  print(ch)

如何判斷一個對象是可迭代對象呢?方法是通過collections模塊的Iterable類型判斷:

>>> from collections import Iterable
>>> isinstance("abc", Iterable) # str是否可迭代
True
>>> isinstance([1,2,3], Iterable) # list是否可迭代
True
>>> isinstance(123, Iterable) # 整數(shù)是否可迭代
False
# Python內(nèi)置的enumerate函數(shù)可以把一個list變成索引-元素對
for i, value in enumerate(["A", "B", "C"]):
  print(i, value)
# 在for循環(huán)中,引用了兩個變量
 for x, y in [(1, 1), (2, 4), (3, 9)]:
   print(x, y)
列表生成式
List Comprehensions,是Python內(nèi)置的非常簡單卻強大的可以用來創(chuàng)建list的生成式
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> L = []
>>> for x in range(1, 11):
    L.append(x * x)
>>>[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# for循環(huán)后面加條件判斷
>>>[x * x for x in range(1, 11) if x % 2 == 0]
[4, 16, 36, 64, 100]
# 兩層循環(huán)
[m + n for m in "ABC" for n in "XYZ"]
["AX", "AY", "AZ", "BX", "BY", "BZ", "CX", "CY", "CZ"]

import os # 導(dǎo)入os模塊,模塊的概念后面講到
>>> [d for d in os.listdir(".")] # os.listdir可以列出文件和目錄

for循環(huán)其實可以同時使用兩個甚至多個變量

d = {"x": "A", "y": "B", "z": "C" }
 for k, v in d.items():
   print(k, "=", v)
[k + "=" + v for k, v in d.items()]
L = ["Hello", "World", "IBM", "Apple"]
[s.lower() for s in L] #大寫變小寫
生成器

如果列表元素可以按照某種算法推算出來,那我們是否可以在循環(huán)的過程中不斷推算出后續(xù)的元素呢?這樣就不必創(chuàng)建完整的list,從而節(jié)省大量的空間。在Python中,這種一邊循環(huán)一邊計算的機制,稱為生成器:generator。

>>> L = [x * x for x in range(10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> g = (x * x for x in range(10))
>>> g
 at 0x1022ef63
next(g)

for n in g:
  print(n)

創(chuàng)建L和g的區(qū)別僅在于最外層的[]和(),L是一個list,而g是一個generator。

可以通過next()函數(shù)獲得generator的下一個返回值:

著名的斐波拉契數(shù)列(Fibonacci),除第一個和第二個數(shù)外,任意一個數(shù)都可由前兩個數(shù)相加得到,函數(shù)

def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        print(b)
        a, b = b, a + b
        n = n + 1
    return "done"
    

把fib函數(shù)變成generator,只需要把print(b)改為yield b就可以了:

def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1
    return "done"

>>> f = fib(6)
>>> f

最難理解的就是generator和函數(shù)的執(zhí)行流程不一樣。
函數(shù)是順序執(zhí)行,遇到return語句或者最后一行函數(shù)語句就返回。
generator的函數(shù),在每次調(diào)用next()的時候執(zhí)行,遇到y(tǒng)ield語句返回,再次執(zhí)行時從上次返回的yield語句處繼續(xù)執(zhí)行。
用for循環(huán)調(diào)用generator時,發(fā)現(xiàn)拿不到generator的return語句的返回值。如果想要拿到返回值,必須捕獲StopIteration錯誤,返回值包含在StopIteration的value中:

>>> g = fib(6)
 while True:
     try:
       x = next(g)
        print("g:", x)
    except StopIteration as e:
       print("Generator return value:", e.value)       break
迭代器

凡是可作用于for循環(huán)的對象都是Iterable類型;

凡是可作用于next()函數(shù)的對象都是Iterator類型,它們表示一個惰性計算的序列;

集合數(shù)據(jù)類型如list、dict、str等是Iterable但不是Iterator,不過可以通過iter()函數(shù)獲得一個Iterator對象。

for x in [1, 2, 3, 4, 5]:
    pass
實際上完全等價于:

# 首先獲得Iterator對象:
it = iter([1, 2, 3, 4, 5])
# 循環(huán):
while True:
    try:
        # 獲得下一個值:
        x = next(it)
    except StopIteration:
        # 遇到StopIteration就退出循環(huán)
        break

使用isinstance()判斷一個對象是否是Iterable對象:

>>> from collections import Iterable
>>> isinstance([], Iterable)
True
>>> isinstance({}, Iterable)
True
>>> isinstance("abc", Iterable)
True
>>> isinstance((x for x in range(10)), Iterable)
True
>>> isinstance(100, Iterable)
False

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/41592.html

相關(guān)文章

  • Python3基礎(chǔ)知識

    摘要:基礎(chǔ)知識基礎(chǔ)語法基礎(chǔ)知識編程第一步基礎(chǔ)知識基本數(shù)據(jù)類型基礎(chǔ)知識解釋器基礎(chǔ)知識注釋基礎(chǔ)知識運算符基礎(chǔ)知識數(shù)字基礎(chǔ)知識字符串基礎(chǔ)知識列表基礎(chǔ)知識元組基礎(chǔ)知識字典基礎(chǔ)知識條件控制基礎(chǔ)知識循環(huán)基礎(chǔ)知識迭代器與生成器基礎(chǔ)知識函數(shù)基礎(chǔ)知識數(shù)據(jù)結(jié)構(gòu)基礎(chǔ)知 Python3基礎(chǔ)知識 | 基礎(chǔ)語法?Python3基礎(chǔ)知識 | 編程第一步?Python3基礎(chǔ)知識 | 基本數(shù)據(jù)類型Python3基礎(chǔ)知識 | ...

    freecode 評論0 收藏0
  • Python3基礎(chǔ)知識

    摘要:基礎(chǔ)知識基礎(chǔ)語法基礎(chǔ)知識編程第一步基礎(chǔ)知識基本數(shù)據(jù)類型基礎(chǔ)知識解釋器基礎(chǔ)知識注釋基礎(chǔ)知識運算符基礎(chǔ)知識數(shù)字基礎(chǔ)知識字符串基礎(chǔ)知識列表基礎(chǔ)知識元組基礎(chǔ)知識字典基礎(chǔ)知識條件控制基礎(chǔ)知識循環(huán)基礎(chǔ)知識迭代器與生成器基礎(chǔ)知識函數(shù)基礎(chǔ)知識數(shù)據(jù)結(jié)構(gòu)基礎(chǔ)知 Python3基礎(chǔ)知識 | 基礎(chǔ)語法?Python3基礎(chǔ)知識 | 編程第一步?Python3基礎(chǔ)知識 | 基本數(shù)據(jù)類型Python3基礎(chǔ)知識 | ...

    z2xy 評論0 收藏0
  • 編程零基礎(chǔ)應(yīng)當如何開始學(xué)習(xí) Python?

    摘要:首先,在學(xué)習(xí)之前一定會考慮一個問題版本選擇對于編程零基礎(chǔ)的人來說,選擇。建議從下面課程開始教程標準庫官方文檔非常貼心地提供中文翻譯首先需要學(xué)習(xí)的基礎(chǔ)知識,下載安裝導(dǎo)入庫字符串處理函數(shù)使用等等。 提前說一下,這篇福利多多,別的不說,直接讓你玩回最有手感的懷舊游戲,參數(shù)貼圖很方便自己可以根據(jù)喜好修改哦。 本篇通過以下四塊展開,提供大量資源對應(yīng)。 showImg(https://segmen...

    JackJiang 評論0 收藏0
  • 基礎(chǔ)如何學(xué)爬蟲技術(shù)

    摘要:楚江數(shù)據(jù)是專業(yè)的互聯(lián)網(wǎng)數(shù)據(jù)技術(shù)服務(wù),現(xiàn)整理出零基礎(chǔ)如何學(xué)爬蟲技術(shù)以供學(xué)習(xí),。本文來源知乎作者路人甲鏈接楚江數(shù)據(jù)提供網(wǎng)站數(shù)據(jù)采集和爬蟲軟件定制開發(fā)服務(wù),服務(wù)范圍涵蓋社交網(wǎng)絡(luò)電子商務(wù)分類信息學(xué)術(shù)研究等。 楚江數(shù)據(jù)是專業(yè)的互聯(lián)網(wǎng)數(shù)據(jù)技術(shù)服務(wù),現(xiàn)整理出零基礎(chǔ)如何學(xué)爬蟲技術(shù)以供學(xué)習(xí),http://www.chujiangdata.com。 第一:Python爬蟲學(xué)習(xí)系列教程(來源于某博主:htt...

    KunMinX 評論0 收藏0

發(fā)表評論

0條評論

Ashin

|高級講師

TA的文章

閱讀更多
最新活動
閱讀需要支付1元查看
<