Python 函數進階

來源:互聯網
上載者:User

標籤:bubuko   ros   參數   red   增加   寫入   class   mic   決定   

一、函數即變數

def say(name):
print(name)
ybq = say #可以被賦值給其他變數
ybq(‘Amily‘) #調用函數

函數名:say 

函數體:第1-2行

傳回值:return 後的值

函數的記憶體位址:當函數體被讀進記憶體後的儲存位置,它由標識符即函數名say引用,
                                                   也就是說say指向的是函數體在記憶體內的儲存位置。

函數名加括弧:  例如say(),函數的調用方法,只有見到這個括弧,程式會根據
                                                   函數名從記憶體中找到函數體,然後執行它

函數名、函數加括弧可以被當做參數傳遞,也可以被當做傳回值return,有沒有括弧是兩個截然不同的意思

def say(name):#定義函數
print(name)

ybq = say #可以被賦值給其他變數
ybq(‘Amily‘) #調用函數
print(say) # 列印函數的記憶體位址
print(type(say)) #列印函數的類型
print(id(say)) #列印函數的id

輸出結果:

Amily
<function say at 0x0000000000B301E0>
<class ‘function‘>
11731424

二、內建函數:map/filter/sorted 

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

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

執行個體1:

def func(a): #求偶數
if a%2==0:
return True
else:
return False
nums = [x for x in range(11)]
all_res = []
res = map(func,nums)
res1 = filter(func,nums)
print(list(res)) #迴圈調用函數,然後把每次函數處理的結果,放到一個list裡面返回

print(list(res1))

輸出結果:

[True, False, True, False, True, False, True, False, True, False, True]
[0, 2, 4, 6, 8, 10]

執行個體二:(lambda  匿名函數)

res = filter(lambda x: x > 5, [12, 3, 12, 2, 1, 2, 35])
res1 = map(lambda x: x > 5, [1, 2, 3, 4, 5, 6])
print(list(res))
print(list(res1))
輸出結果:

[12, 12, 35]
[False, False, False, False, False, True]

sorted()   #升序排列

sorted(  ,reverse = True)  #降序排列

 

輸出結果:

三、處理 json 

Python JSON模組可以直接處理單一資料型別(string、unicode、int、float、list、tuple、dict)。

json.dumps()方法返回一個str對象,編碼過程中會存在從python原始類型向json類型的轉化過程,具體的轉化對照如下

  需要注意的是,json字串中的字典類型的key必須要用雙引號“”json.loads()才能正常解析

 1,將Python 資料結構轉換成 Json 格式(編碼)  json.dumps()

indent參數是縮排的意思,它可以使資料的儲存格式更優雅、可讀性更強,這是通過增加一些冗餘的空格進行填充的。但是在解碼(json.loads())時,空白填充會被刪除。

loads時會將dumps時增加的intent 填充空格去除

ensure_ascii  參數 顯示中文

執行個體:

import json
d = {
‘car‘:{‘color‘:‘red‘,‘price‘:100,‘count‘:50},
‘car1‘:{‘color‘:‘red‘,‘price‘:100,‘count‘:50},
‘car2‘:{‘color‘:‘red‘,‘price‘:100,‘count‘:50},
‘car3‘:{‘color‘:‘red‘,‘price‘:100,‘count‘:50},
‘car4‘:{‘color‘:‘red‘,‘price‘:100,‘count‘:50},
‘car5‘:{‘color‘:‘red‘,‘price‘:100,‘count‘:50},
}
res = json.dumps(d,indent=8,ensure_ascii=False) #把list、字典轉成json,indent多少縮排,ensure_ascii可以顯示中文
f1 = open(‘f1‘,‘w‘,encoding=‘utf-8‘)
f1.write(res)

輸出結果:

2,將Json 格式 轉換成 Python 資料結構(解碼) json.loads()

執行個體:

f1 = open(‘f1‘,encoding=‘utf-8‘)
res = f1.read()
dict_res = json.loads(res) #把json串變成python的資料類型
print(dict_res)
print(type(dict_res))

輸出結果:

{‘car3‘: {‘color‘: ‘red‘, ‘count‘: 50, ‘price‘: 100}, ‘car‘: {‘color‘: ‘red‘, ‘count‘: 50, ‘price‘: 100}, ‘car1‘: {‘color‘: ‘red‘, ‘count‘: 50, ‘price‘: 100},

‘car5‘: {‘color‘: ‘red‘, ‘count‘: 50, ‘price‘: 100}, ‘car2‘: {‘color‘: ‘red‘, ‘count‘: 50, ‘price‘: 100}, ‘car4‘: {‘color‘: ‘red‘, ‘count‘: 50, ‘price‘: 100}}
<class ‘dict‘>

3,如果要處理的是檔案而不是字串,可以使用 json.dump() 和 json.load() 來編碼和解碼JSON資料

寫入json 格式的檔案
f1 = open(‘f1‘,‘w‘,encoding=‘utf-8‘)
json.dump(d,f1,ensure_ascii=False,indent=4)
#自動幫你寫入檔案,第一個參數是資料,第二個是檔案對象
讀取檔案
f1 = open(‘f1‘,encoding=‘utf-8‘)
print(json.load(f1))

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.