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

          替代for循環(huán),讓Python代碼更pythonic !

          共 5901字,需瀏覽 12分鐘

           ·

          2023-02-18 09:59

          來源:Python 技術(shù)「ID: pythonall」

          e8cc3f3e22209d83400b73b24ef6bf5e.webp


          為什么要挑戰(zhàn)自己在代碼里不寫 for loop?因為這樣可以迫使你去學(xué)習(xí)使用比較高級、比較地道的語法或 library。文中以 python 為例子,講了不少大家其實在別人的代碼里都見過、但自己很少用的語法。


          自從我開始探索 Python 中驚人的語言功能已經(jīng)有一段時間了。一開始,我給自己一個挑戰(zhàn),目的是讓我練習(xí)更多的 Python 語言功能,而不是使用其他編程語言的編程經(jīng)驗。這讓事情變得越來越有趣!代碼變得越來越簡潔,代碼看起來更加結(jié)構(gòu)化和規(guī)范化。下面我將會介紹這些好處。


          通常如下使用場景中會用到 for 循環(huán):


          • 在一個序列來提取一些信息。

          • 從一個序列生成另一個序列。
          • 寫 for 已成習(xí)慣。



          幸運的是,Python 已經(jīng)有很多工具可以幫助你完成這些工作,你只需要轉(zhuǎn)移你的思路,并以不同的角度來思考它。
          通過避免編寫 for 循環(huán),你可以獲得什么好處:


          • 較少的代碼量
          • 更好的代碼可讀性
          • 更少的縮進(對 Python 還是很有意義的)



          我們來看一下下面的代碼結(jié)構(gòu):
                
                  
                    # 1
                  
                
                
                  with ...:
                
                
                      for ...:
                
                
                          if ...:
                
                
                              try:
                
                
                              except:
                
                
                          else:
                
              

          在這個例子中,我們正在處理多層嵌套的代碼,這很難閱讀。這個例子使用了多層嵌套的代碼。我在這段代碼中發(fā)現(xiàn)它無差別使用縮進把管理邏輯(with, try-except)和業(yè)務(wù)邏輯(for, if)混在一起。如果你遵守只對管理邏輯使用縮進的規(guī)范,那么核心業(yè)務(wù)邏輯應(yīng)該立刻脫離出來。
          "扁平結(jié)構(gòu)比嵌套結(jié)構(gòu)更好" - The Zen of Python
          可以使用的已有的工具來替換 for 循環(huán)
          1.List Comprehension / Generator 表達式
          我們來看一個簡單的例子。如果你想將一個數(shù)組轉(zhuǎn)換為另一個數(shù)組:
                
                  result = []
                
                
                  for item in item_list:
                
                
                      new_item = do_something_with(item)
                
                
                      result.append(item)
                
              

          如果你喜歡 MapReduce,你也可以使用 map,或者 Python 中的 List Comprehension:
                
                  result = [do_something_with(item) for item in item_list]
                
              

          同樣,如果您只想迭代數(shù)組中的元素,也可以使用一樣的代碼 Generator Expression。result = (do_something_with(item) for item in item_list)
          2.函數(shù)
          如果您想要將一個數(shù)組映射成另外數(shù)組,只需調(diào)用 map 函數(shù),就可以用一個更高級、更實用的編程方式解決這個問題。
                
                  doubled_list = map(lambda x: x * 2, old_list)
                
              

          如果要將序列減少為單個,請使用 reduce
                
                  from functools import reduce
                
                
                  summation = reduce(lambda x, y: x + y, numbers)
                
              

          另外,許多 Python 內(nèi)置函數(shù)都會使用 iterables:
                
                  >>> a = list(range(10))
                
                
                  >>> a
                
                
                  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
                
                
                  >>> all(a)
                
                
                  False
                
                
                  >>> any(a)
                
                
                  True
                
                
                  >>> max(a)
                
                
                  
                    9
                  
                
                
                  >>> min(a)
                
                
                  
                    0
                  
                
                
                  >>> list(filter(bool, a))
                
                
                  [1, 2, 3, 4, 5, 6, 7, 8, 9]
                
                
                  >>> set(a)
                
                
                  {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
                
                
                  >>> dict(zip(a,a))
                
                
                  {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}
                
                
                  >>> sorted(a, reverse=True)
                
                
                  [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
                
                
                  >>> str(a)
                
                
                  
                    '[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]'
                  
                
                
                  >>> sum(a)
                
                
                  
                    45
                  
                
              




          3.Extract Functions or Generators
          上述兩種方法是很好的處理更簡單的邏輯。更復(fù)雜的邏輯怎么樣?作為程序員,我們編寫函數(shù)來抽離出復(fù)雜的業(yè)務(wù)。相同的想法適用于此。如果你是這樣寫的:
                
                  results = []
                
                
                  for item in item_list:
                
                
                      # setups
                
                
                      # condition
                
                
                      # processing
                
                
                      # calculation
                
                
                      results.append(result)
                
              

          顯然你對一個代碼塊添加了太多的責任。相反,我建議你做:
                
                  
                    def process_item(item):
                  
                
                
                      # setups
                
                
                      # condition
                
                
                      # processing
                
                
                      # calculation
                
                
                  ????return?result
                
                
                  
                    
          results = [process_item(item) for item in item_list]

          如果換成嵌套函數(shù)會如何
                
                  results = []
                
                
                  for i in range(10):
                
                
                      for j in range(i):
                
                
                          results.append((i, j))
                
              

          換成 List Comprehension 來實現(xiàn)是這樣的:
                
                  results = [(i, j)
                
                
                             for i in range(10)
                
                
                             for j in range(i)]
                
              

          如果你的代碼塊需要記錄一些內(nèi)部狀態(tài)
                
                  
                    # finding the max prior to the current item
                  
                
                
                  a = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
                
                
                  results = []
                
                
                  current_max = 0
                
                
                  for i in a:
                
                
                      current_max = max(i, current_max)
                
                
                  ????results.append(current_max)
                
                
                  
                    
          # results = [3, 4, 6, 6, 6, 9, 9, 9, 9, 9]

          我們使用 generator 來實現(xiàn)這一點:
                
                  def max_generator(numbers):
                
                
                      current_max = 0
                
                
                      for i in numbers:
                
                
                          current_max = max(i, current_max)
                
                
                  
                    ????????yield?current_max
                  
                
                
                  
                    
          a = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8] results = list(max_generator(a))

          讀者可能要問 “等等!你在 generator 中用到 for 循環(huán),作弊啊!別急,再看看下面的代碼。
          不要自己寫,itertools 幫你實現(xiàn)了
          這個模塊很簡單,我相信這個模塊在大多數(shù)場景中可以替換你原先的 for 循環(huán)。
          例如,最后一個例子可以重寫為:
                
                  from itertools import accumulate
                
                
                  a = [3, 4, 6, 2, 1, 9, 0, 7, 5, 8]
                
                
                  resutls = list(accumulate(a, max))
                
              

          另外,如果要迭代組合序列,則需要使用product(), permutations(), combinations()。
          結(jié)論
          在大多數(shù)情況下,您都不需要編寫 for 循環(huán)。
          你應(yīng)該避免編寫 for 循環(huán),這樣會有更好的代碼可讀性。
          瀏覽 25
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

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

          手機掃一掃分享

          分享
          舉報
          <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>
                  一道本无码一区 | 天天撸天天干 | 香蕉啪啪视频 | 亲子伦一区二区三区观看方式 | 蜜芽亚洲av无码精品色午夜 |