<output id="qn6qe"></output>

    1. <output id="qn6qe"><tt id="qn6qe"></tt></output>
    2. <strike id="qn6qe"></strike>

      亚洲 日本 欧洲 欧美 视频,日韩中文字幕有码av,一本一道av中文字幕无码,国产线播放免费人成视频播放,人妻少妇偷人无码视频,日夜啪啪一区二区三区,国产尤物精品自在拍视频首页,久热这里只有精品12

      翻譯:《實用的Python編程》06_03_Producers_consumers

      目錄 | 上一節 (6.2 自定義迭代) | 下一節 (6.4 生成器表達式)

      6.3 生產者,消費者和管道

      生成器在設置各種生產者/消費者問題(producer/consumer problems)和數據流管道(pipeline)中非常有用。本節將對此進行討論。

      生產者消費者問題

      生成器與各種形式的 生產者消費者 問題密切相關。

      # Producer
      def follow(f):
          ...
          while True:
              ...
              yield line        # Produces value in `line` below
              ...
      
      # Consumer
      for line in follow(f):    # Consumes value from `yield` above
          ...
      

      yield 語句生成給 for 語句消費的值。

      生成器管道

      你可以使用生成器的這方面特性來設置進程管道(類似于 Unix 管道(pipe))。

      producerprocessingprocessingconsumer

      進程管道包括初始的數據生產者、中間的處理階段、最后的消費者。

      producerprocessingprocessingconsumer

      def producer():
          ...
          yield item
          ...
      

      通常情況下,生產者是一個生成器,盡管也可以是其它的序列列表。yield 將數據輸入管道。

      producerprocessingprocessingconsumer

      def consumer(s):
          for item in s:
              ...
      

      消費者是一個 for 循環,獲取數據(譯注:items)并對數據執行某些操作。

      producerprocessingprocessingconsumer

      def processing(s):
          for item in s:
              ...
              yield newitem
              ...
      

      中間的處理階段同時消費和生產數據。它們可能修改數據流,也可能篩選數據流(丟棄數據)。

      producerprocessingprocessingconsumer

      def producer():
          ...
          yield item          # yields the item that is received by the `processing`
          ...
      
      def processing(s):
          for item in s:      # Comes from the `producer`
              ...
              yield newitem   # yields a new item
              ...
      
      def consumer(s):
          for item in s:      # Comes from the `processing`
              ...
      

      設置管道的代碼如下:

      a = producer()
      b = processing(a)
      c = consumer(b)
      

      你會發現數據逐漸地流向不同的函數。

      練習

      對于本練習,stocksim.py 程序仍需要在后臺運行。并且,你將使用到上一節練習(譯注:練習 6.7)編寫的 follow() 函數。

      練習 6.8:創建一個簡單的管道

      讓我們來看看管道的思想。請創建下面這個函數:

      >>> def filematch(lines, substr):
              for line in lines:
                  if substr in line:
                      yield line
      
      >>>
      

      filematch() 函數除了不再打開文件,幾乎與上一節練習的第一個生成器示例完全相同——僅僅對作為參數給出的行序列進行操作?,F在,請嘗試如下操作:

      >>> from follow import follow
      >>> lines = follow('Data/stocklog.csv')
      >>> ibm = filematch(lines, 'IBM')
      >>> for line in ibm:
              print(line)
      
      ... wait for output ...
      

      雖然輸出可能需要一定時間才會出現,但是,最后你一定會看到包含 IBM 數據的行。

      練習 6.9:創建一個復雜的管道

      通過執行更多操作來進一步理解管道的思想。

      >>> from follow import follow
      >>> import csv
      >>> lines = follow('Data/stocklog.csv')
      >>> rows = csv.reader(lines)
      >>> for row in rows:
              print(row)
      
      ['BA', '98.35', '6/11/2007', '09:41.07', '0.16', '98.25', '98.35', '98.31', '158148']
      ['AA', '39.63', '6/11/2007', '09:41.07', '-0.03', '39.67', '39.63', '39.31', '270224']
      ['XOM', '82.45', '6/11/2007', '09:41.07', '-0.23', '82.68', '82.64', '82.41', '748062']
      ['PG', '62.95', '6/11/2007', '09:41.08', '-0.12', '62.80', '62.97', '62.61', '454327']
      ...
      

      這非常有趣。你在這里可以看到, follow() 函數的輸出被傳遞到 csv.reader()函數,并且,我們現在得到了一系列拆分的行。

      練習 6.10:創建更多管道組件

      讓我們把這樣的思想擴展到更大的管道中。首先,創建 ticker.py 文件,然后在 ticker.py 文件里面創建一個函數,像上面一樣讀取 CSV 文件:

      # ticker.py
      
      from follow import follow
      import csv
      
      def parse_stock_data(lines):
          rows = csv.reader(lines)
          return rows
      
      if __name__ == '__main__':
          lines = follow('Data/stocklog.csv')
          rows = parse_stock_data(lines)
          for row in rows:
              print(row)
      

      接著,創建一個選擇特定列的新函數:

      # ticker.py
      ...
      def select_columns(rows, indices):
          for row in rows:
              yield [row[index] for index in indices]
      ...
      def parse_stock_data(lines):
          rows = csv.reader(lines)
          rows = select_columns(rows, [0, 1, 4])
          return rows
      

      再次運行程序,你應該可以看到輸出縮小如下:

      ['BA', '98.35', '0.16']
      ['AA', '39.63', '-0.03']
      ['XOM', '82.45','-0.23']
      ['PG', '62.95', '-0.12']
      ...
      

      再接著,創建一個生成器函數以轉換數據類型并構建字典。示例:

      # ticker.py
      ...
      
      def convert_types(rows, types):
          for row in rows:
              yield [func(val) for func, val in zip(types, row)]
      
      def make_dicts(rows, headers):
          for row in rows:
              yield dict(zip(headers, row))
      ...
      def parse_stock_data(lines):
          rows = csv.reader(lines)
          rows = select_columns(rows, [0, 1, 4])
          rows = convert_types(rows, [str, float, float])
          rows = make_dicts(rows, ['name', 'price', 'change'])
          return rows
      ...
      

      再次運行程序,你應該能夠看到像下面這樣的字典流:

      { 'name':'BA', 'price':98.35, 'change':0.16 }
      { 'name':'AA', 'price':39.63, 'change':-0.03 }
      { 'name':'XOM', 'price':82.45, 'change': -0.23 }
      { 'name':'PG', 'price':62.95, 'change':-0.12 }
      ...
      

      練習 6.11:篩選數據

      創建一個篩選數據的函數。示例:

      # ticker.py
      ...
      
      def filter_symbols(rows, names):
          for row in rows:
              if row['name'] in names:
                  yield row
      

      使用該函數可以篩選出投資組合中的股票:

      import report
      portfolio = report.read_portfolio('Data/portfolio.csv')
      rows = parse_stock_data(follow('Data/stocklog.csv'))
      rows = filter_symbols(rows, portfolio)
      for row in rows:
          print(row)
      

      練習 6.12:整合所有的代碼

      請在 ticker.py 文件中編寫函數 ticker(portfile, logfile, fmt) ,該函數根據給定的投資組合、日志文件和表格格式創建實時的股票報價器。示例:

      >>> from ticker import ticker
      >>> ticker('Data/portfolio.csv', 'Data/stocklog.csv', 'txt')
            Name      Price     Change
      ---------- ---------- ----------
              GE      37.14      -0.18
            MSFT      29.96      -0.09
             CAT      78.03      -0.49
              AA      39.34      -0.32
      ...
      
      >>> ticker('Data/portfolio.csv', 'Data/stocklog.csv', 'csv')
      Name,Price,Change
      IBM,102.79,-0.28
      CAT,78.04,-0.48
      AA,39.35,-0.31
      CAT,78.05,-0.47
      ...
      

      討論

      心得體會:你可以創建各種生成器函數,并把它們鏈接在一起執行涉及數據流的管道處理。另外,你可以創建一個函數,把一系列的管道階段打包到一個單獨的函數中調用(例如 parse_stock_data() 函數)。

      目錄 | 上一節 (6.2 自定義迭代) | 下一節 (6.4 生成器表達式)

      注:完整翻譯見 https://github.com/codists/practical-python-zh

      posted @ 2021-03-17 23:54  codists  閱讀(97)  評論(0)    收藏  舉報
      主站蜘蛛池模板: 无遮挡aaaaa大片免费看| 久久人与动人物a级毛片| 午夜免费福利小电影| 最近中文字幕日韩有码| 久久人妻夜夜做天天爽| 少妇厨房愉情理9仑片视频| 少妇愉情理伦片高潮日本 | 久久精品国产免费观看频道| 国产黄色一区二区三区四区 | 亚洲精品国产熟女久久久| 香蕉EEWW99国产精选免费| 乾安县| 国产精品无码一区二区牛牛| 国产成AV人片久青草影院| 尹人香蕉久久99天天拍| 亚洲a片无码一区二区蜜桃| 久久一区二区中文字幕| 道孚县| 精品国产伦理国产无遮挡| 人妻丝袜AV中文系列先锋影音| 人妻中文字幕不卡精品| 午夜免费视频国产在线| 亚洲激情一区二区三区在线| 麻豆国产va免费精品高清在线| 国内综合精品午夜久久资源| 国产乱人偷精品人妻a片| 免费人妻av无码专区| 重口SM一区二区三区视频| 亚洲精品无码乱码成人| 国产 麻豆 日韩 欧美 久久| 日韩亚洲精品国产第二页| 国产成人久久综合一区| 狠狠做五月深爱婷婷天天综合| 热久久美女精品天天吊色| 亚洲精品97久久中文字幕无码 | 人妻无码| 网友自拍视频一区二区三区 | 久久午夜夜伦鲁鲁片免费无码| 激情国产一区二区三区四区| 成年女人片免费视频播放A| 昆山市|