python學習筆記4-內建函數、匿名函數、json處理

來源:互聯網
上載者:User

標籤:exe   eval   學習筆記   map   ascii   布爾類型   callable   item   bin   

        print(all([1,2,3,4]))#判斷可迭代的對象裡面的值是否都為真                print(any([0,1,2,3,4]))#判斷可迭代的對象裡面的值是否有一個為真        print(bin(10))#十進位轉二進位        print(bool(‘s‘))#把一個對象轉換成布爾類型        print(bytearray(‘abcde‘,encoding=‘utf-8‘))#把字串變成一個可修改的bytes        print(callable(‘aa‘))#判斷傳入的對象是否可調用        print(chr(10))#列印數字對應的ascii        print(ord(‘b‘))#列印字串對應的ascii碼        print(dict(a=1,b=2))#轉換字典        print(dir(1))#列印傳入對象的可調用方法        print(eval(‘[]‘))#執行python代碼,只能執行簡單的,定義資料類型和運算        print(exec(‘def a():pass‘))#執行python代碼        print(filter(lambda x:x>5,[12,3,12,2,1,2,35]))#把後面的迭代對象根據前面的方法篩選        print(map(lambda x:x>5,[1,2,3,4,5,6]))        print(frozenset({1,2,3,3}))#定義一個不可修改的集合        print(globals())#返回程式內所有的變數,返回的是一個字典        print(locals())#返回局部變數        print(hash(‘aaa‘))#把一個字串雜湊成一個數字        print(hex(111))#數字轉成16進位        print(max(111,12))#取最大值        print(oct(111))#把數字轉換成8進位        print(round(11.11,2))#取幾位小數        print(sorted([2,31,34,6,1,23,4]))#排序        dic={1:2,3:4,5:6,7:8}        print(sorted(dic.items()))#按照字典的key排序        print(sorted(dic.items(),key=lambda x:x[1]))#按照字典的value排序        __import__(‘decorator‘)#匯入一個模組

二、filter和map

#filterdef func(a):    if a%2==0:        return a    else:        return Falsenums=[x for x in range(11)]res=filter(func,nums)print(list(res))#filter:迴圈調用函數,filter只儲存返回真的(非空即真,非零即真)

  

#map# all_res = []# for num in nums:# res = func(num)# all_res.append(res)## res = map(func,nums) ### print(list(res))#迴圈調用函數,然後把每次函數處理的結果,放到一個list裡面返回

 三、匿名函數

        s = lambda x,y:x+y#冒號號前面的x,y是入參,冒號後面的是傳回值        print(s(1,9))#因為函數即變數,如果沒有定一個變數把lambda存起來的話,它就不在記憶體裡,沒法執行,所有把它放到s這個變數裡面

四、json處理

    import json        dic = {"name":"niuniu","age":18}    print(json.dumps(dic))#把字典轉成json串    fj = open(‘a.json‘,‘w‘)     print(json.dump(dic,fj))#把字典轉換成的json串寫到一個檔案裡面    s_json = ‘{"name":"niuniu","age":20,"status":true}‘    print(json.loads(s_json))#把json串轉換成字典    fr = open(‘b.json‘,‘r‘)    print(json.load(fr))#從檔案中讀取json資料,然後轉成字典

 

python學習筆記4-內建函數、匿名函數、json處理

聯繫我們

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