<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>

          10個(gè)簡潔的Python編碼技巧

          共 3108字,需瀏覽 7分鐘

           ·

          2020-11-16 13:44

          點(diǎn)擊上方小白學(xué)視覺”,選擇加"星標(biāo)"或“置頂

          重磅干貨,第一時(shí)間送達(dá)

          Python是一種十分簡潔而又美麗的語言,它提供了多種方法來完成相同的任務(wù),這使我們很容易沉醉于它。但是一些不好的習(xí)慣也會(huì)破壞Python的簡潔,很容易讓事情變得更復(fù)雜。下面是10個(gè)小編推薦的編程小技巧,讓我們的Python代碼更漂亮。


          1.?學(xué)會(huì)使用文檔字符串


          使用"""三重雙引號(hào)"""來編寫文檔字符串,這些文檔字符串可以清楚地說明函數(shù),模塊和程序的全部目的。

          def get_percent_sales(product,sales,region):“““Return the product Sales volumes in percent of total in country.Get percentage of product sales of the region.This function gets the product and corresponding sales by region and returns a percent sales of the region by total sales in that country. Region input is accepted only by city. Districts are not accepted. If city name is not found, exception is thrown.         Parameters:              product (str) : Product name             sales (int) : Sales Volume         Returns:              percent_sales (float): Percent of total sales of                                        product."""

          2.?讓代碼的邏輯更加直觀易讀


          不推薦:

          if is_white == Falseif not is_white == False

          推薦:

          is_white = Trueif is_white:else:

          3.?使用“.join”代替“+”實(shí)現(xiàn)字符串連接


          不推薦:

          my_name = ‘firstname’+ ‘ ‘ + ‘lastname’

          推薦:

          my_name = " ".join(['firstname','lastname'])

          4.?使用List代替for循環(huán)讀取數(shù)組

          numbers = [1,2,3,4,5,6,7,8,9,10]

          不推薦:

          even_halves = [ ]for num in numbers:    if num%2 == 0:       even_halves.append(num/2)print(even_halves)

          推薦:

          even_halves = [num/2 for num in numbers if num%2==0]

          5.?使用def函數(shù)代替lambda給變量賦值


          不推薦:

          squared = lamdba x: x**2

          推薦:

          def squared(x):   return x**2

          6.?不要把代碼都擠在一行


          注意文本換行!


          不推薦:

          df = pd.read_excel('This/extremely/long/file/path/that/extends/ /to/the/next/line/and/screws/with/indentation.xlsx')mylist = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20000,30000,3100000320000]

          推薦:

          filepath = "this/sweet/line/" \           "continued/prettily/"\           "looksbetter.xlsx"df = pd.read_excel(filepath)my_list = [1,2,3,4,5,6,7,8,9,10,11,          12,13,14,15,16,17,18,19,          20000,30000,3100000,320000]if this_happens or that_happens \   or these_happen:      print('blah')else:   print('the other blah')

          7.?多用range,少用List


          不推薦:

          indices = [0,2,4,6,8,10]for idX in indices:    print(name[idX])

          推薦:

          for idX in range(0,12,2):    print(name[idX])

          8.?在“try”模塊下保留最精簡的代碼


          不推薦:

          try:   names = get_data(students, classroom)   numbers = get_scores(students, classroom)   return names,numbersexcept KeyError:

          推薦:

          try:    names = get_data(students, classroom)    numbers = get_scores(students, classroom)except KeyError:    print('That's not a student in this classroom!')return names, numbers

          9.?更多地使用set


          如果在當(dāng)前情況下不需要大量功能,則最好使用集合而不是其他數(shù)據(jù)結(jié)構(gòu)。

          data = {‘find_this’, ‘a(chǎn)mong’, ‘a(chǎn)ll_the’,'other',’data’}if‘find_this’ in data:   print(‘this exists!’)long_stuff = [‘this’,’list’,’list’,’is’,             ’enormous’,’oh’,’my’,’god’,             ’god’,’what’,’is’,             ’unique’,’unique’]unique_values = set(long_stuff)

          10.?使用zip迭代多個(gè)列表

          students = [‘tom’,’dick’,’harry’,’larry’,’tim’,’benny’]scores = [100,20,40,60,30,40]

          不推薦:

          for i in range(len(students)):    print(student[i],scores[i]

          推薦:

          for student,score in zip(students,scores):    print(student,score)

          這就是一些使用python的小技巧。遵循良好的編程風(fēng)格,做一個(gè)優(yōu)秀的程序員!


          ·? END? ·

          瀏覽 22
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <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>
                  人妻123区 | 国产黄色电影在线免费观看 | 一本色道久久综合无码 | 人人看人人干人人过人人 | 国产色情一级一区二区直播 |