<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          關(guān)于Python的20個奇技淫巧

          共 3600字,需瀏覽 8分鐘

           ·

          2021-04-10 10:17

          一、快速實現(xiàn)字頻統(tǒng)計

          from collections import Counter
          words = '''我明白你的意思,你的意思就是想意思意思,但是你不明白我的意思,我的意思是你不用意思意思。'''word_counts = Counter(words) top_three = word_counts.most_common(3) print(top_three)
          # 輸出:[('意', 8), ('思', 8), ('你', 4)]

          二、漢字轉(zhuǎn)拼音

          import pypinyinwords = "床前明月光"pypinyin.pinyin(words)
          # 輸出:[['chuáng'], ['qián'], ['míng'], ['yuè'], ['guāng']]

          三、查看某個文件夾里是否有python文件(或其他格式文件)

          import os files = os.listdir("E:\\testfile\\") if any(name.endswith('.py') for name in files):    print(1)

          四、快速打印字符串


          row = ["我", "愛", "python"] print(*row,sep="")
          # 輸出:我愛python

          五、計算兩個日期間隔天數(shù)

          from datetime import dated1 = date(2020,1,1) d2 = date(2020,9,13) print(abs(d2-d1).days)
          # 輸出:256

          六、字符串拆解為鍵值對

          比如'x=11,y=20'拆解成{'x'42.0'y'1.0}
          kvp = lambda elem,t,i: t(elem.split('=')[i]) parse_kvp_str = lambda args : dict([(kvp(elem,str,0), kvp(elem,float,1)) for elem in args.split(',')]) parse_kvp_str('x=11,y=20') 
          # 輸出:{'x': 42.0, 'y': 1.0}

          七、變量值交換

          a = 1b = 2a, b = b, a

          八、將值追加到字典某個鍵下的列表中

          d = {} d.setdefault(2, []).append(23) d.setdefault(2, []).append(11) d[2] 
          # 輸出:[23, 11]

          九、返回列表中出現(xiàn)次數(shù)最多的元素

          test = [1, 2, 3, 5, 2, 2, 3, 1, 2, 6, 2] print(max(set(test), key = test.count)) 
          # 輸出:2

          十、查看某個變量占用內(nèi)存的大小

          import sys x = 1print(sys.getsizeof(x)) 
          # 輸出:28

          十一、隨機返回幾個字母組成的單詞

          import string, random randword = lambda n: "".join([random.choice(string.ascii_letters) for i in range(n)])
          # 輸出:'qsNWZF'

          十二、從混亂的字符串中分解出單詞

          words = lambda text: ''.join(c if c.isalnum() else ' ' for c in text).split() words('Johnny.Appleseed!is:a*good&farmer') 
          # 輸出:['Johnny''Appleseed''is''a''good''farmer']

          十三、打印進度條

          import time import sys for progress in range(100):   time.sleep(0.1)   sys.stdout.write("Download progress: %d%%   \r" % (progress) )    sys.stdout.flush() 

          十四、快速反轉(zhuǎn)字符串

          a = 'Python is a powerful languange.'print(a[::-1])
          # 輸出:.egnaugnal lufrewop a si nohtyP

          十五、找出兩個列表中不一樣的元素

          list1 = ['Scott', 'Eric', 'Kelly', 'Emma', 'Smith']list2 = ['Scott', 'Eric', 'Kelly']
          set1 = set(list1)set2 = set(list2)
          list3 = list(set1.symmetric_difference(set2))print(list3)
          # 輸出:['Emma', 'Smith']

          十六、刪除列表中的重復(fù)項

          listNumbers = [20, 22, 24, 26, 28, 28, 20, 30, 24]list(set(listNumbers))
          # 輸出:[20, 22, 24, 26, 28, 30]

          十七、將兩個列表變成字典

          ItemId = [54, 65, 76]names = ["Hard Disk", "Laptop", "RAM"]itemDictionary = dict(zip(ItemId, names))print(itemDictionary)
          # 輸出:{54: 'Hard Disk', 65: 'Laptop', 76: 'RAM'}

          十八、移除字符換中的標(biāo)點

          punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~,。!?'''my_str = "你好,!!我的網(wǎng)名叫作:隔-壁-老-王。"
          # 移除標(biāo)點no_punct = ""for char in my_str: if char not in punctuations: no_punct = no_punct + char
          print(no_punct)
          # 輸出:你好我的名字叫作:隔壁老王

          十九、創(chuàng)建一個文件(如果文件不存在)

          import os  
          MESSAGE = '該文件已經(jīng)存在.'TESTDIR = 'testdir'try: home = os.path.expanduser("~") print(home)
          if not os.path.exists(os.path.join(home, TESTDIR)): os.makedirs(os.path.join(home, TESTDIR)) else: print(MESSAGE)except Exception as e: print(e)

          二十、從函數(shù)中返回多個值

          def f():    return 1,2,3,4 
          a,b,c,d = f()print(a,b,c,d)
          # 輸出:1,2,3,4

          推薦閱讀

          (點擊標(biāo)題可跳轉(zhuǎn)閱讀)

          看到這些代碼,我自嘆不如!!!

          通俗易懂之最小二乘法(附matlab和python例子實現(xiàn))

          數(shù)據(jù)處理工具--Pandas模塊

          PyMySQL數(shù)據(jù)庫搭建

          教你用Python制作實現(xiàn)自定義字符大小的簡易小說閱讀器

          小程序云開發(fā)項目的創(chuàng)建與配置

          匯總超全Matplotlib可視化最有價值的 50 個圖表(附 Python 源代碼)(一)

          超詳細講解CTC理論和實戰(zhàn)

          ODBC連接主流數(shù)據(jù)庫的配置方法

          教你用python進行數(shù)字化妝,可愛至極

          加速Python列表和字典,讓你代碼更加高效

          老鐵,三連支持一下,好嗎?↓↓↓


          點分享

          點點贊

          點在

          瀏覽 95
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  欧美一级A片免费看视频小说 | 国产极品久久久 | 长泽梓在线 | 国产内射在线观看 | 久久免费成人视频 |