[英]Understanding flow of execution of Python code
我正在嘗試與Curesra的Data Manipulation Scale:Systems and Algorithms中的python進行家庭分配。 通常,我在理解基本代碼時遇到了問題,這是作為MapReduce alogorythm的示例提出的。 非常感謝您在以下2個地方幫助我理解它。
運行命令后,我厭倦了逐步瀏覽下面兩個文件的代碼流:
python wordcount.py 'data/books.json'
wordcount.py
已打開 mr = MapReduce.MapReduce()
-創建對象 def __init__(self):
MapReduce.py
中的一部分已執行 wordcount.py
def mapper(record):
和def reducer(key,list_of_values):
已創建,但暫時沒有執行 if __name__ == '__main__':
mr.execute(inputdata, mapper, reducer)
-從MapReduce.py
對該函數的調用。 這是我的第一個問題,到目前為止,我們尚未定義mapper或reducer變量/對象。 它只是傳遞給該函數的null / no值,還是我們之前以某種方式定義了此變量,但我錯過了它?
def execute(self, data, mapper, reducer):
在MapReduce.py
mapper(record)
。 所以這是對wordcount.py中函數的引用,對嗎? 但是,如果我們在其他文件中引用了函數,那么是否不應該在文件開頭使用import並定義該函數來自哪個文件呢?
(...)進一步執行代碼
wordcount.py文件:
import MapReduce
import sys
"""
Word Count Example in the Simple Python MapReduce Framework
"""
mr = MapReduce.MapReduce()
# =============================
# Do not modify above this line
def mapper(record):
# key: document identifier
# value: document contents
key = record[0]
value = record[1]
words = value.split()
for w in words:
mr.emit_intermediate(w, 1)
def reducer(key, list_of_values):
# key: word
# value: list of occurrence counts
total = 0
for v in list_of_values:
total += v
mr.emit((key, total))
# Do not modify below this line
# =============================
if __name__ == '__main__':
inputdata = open(sys.argv[1])
mr.execute(inputdata, mapper, reducer)
MapReduce.py文件:
import json
class MapReduce:
def __init__(self):
self.intermediate = {}
self.result = []
def emit_intermediate(self, key, value):
self.intermediate.setdefault(key, [])
self.intermediate[key].append(value)
def emit(self, value):
self.result.append(value)
def execute(self, data, mapper, reducer):
for line in data:
record = json.loads(line)
mapper(record)
for key in self.intermediate:
reducer(key, self.intermediate[key])
#jenc = json.JSONEncoder(encoding='latin-1')
jenc = json.JSONEncoder()
for item in self.result:
print jenc.encode(item)
預先感謝您的幫助。
在python中,所有東西都是一個包含函數的對象,因此您可以將functionA作為參數傳遞給另一個functionB(或類或任何時候),並且如果functionB希望您這樣做,它將假定您使用正確的做法和正常的進行。
就你而言
mr.execute(inputdata, mapper, reducer)
這里的mapper
和reducer
是先前定義的函數,它們作為參數傳遞給MapReduce
類的實例mr
的方法execute
,並且如您所見,該方法將其用作期望的函數。
正是由於這一點,如該代碼所示,您可以通過給用戶提供提供其自己功能的選項,從而使通用代碼進行某種演算,從而可以被許多應用程序以類似方式使用。
一個更通用的例子是函數map
,該函數接收執行某項功能的函數,map不在乎它做什么或它來自哪里,僅接收與map自己接收的參數一樣多的參數(其他表示函數的參數)並返回一個值以使用結果構建一個新列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.