簡體   English   中英

Python:我不理解函數調用函數的順序

[英]Python: I don't understand the order of a function calling a function

我正在關注Joel Grus撰寫的《 Scratch的數據科學》一書,他們描述了以下代碼以創建身份矩陣

def make_matrix(num_rows, num_cols, entry_fn):
    return [[entry_fn(i, j) 
            for j in range(num_cols)]           
            for i in range(num_rows)]

def is_diagonal(i, j):
    return 1 if i == j else 0

identity_matrix = make_matrix(5, 5, is_diagonal)

盡管我可以看到這是如何創建一個身份矩陣的,但我仍然難以准確理解它。

我看到它的方式是,我們調用函數make_matrix帶參數55is_diagonal 此時,代碼將到達is_diagonal(i, j) for j in range(5)is_diagonal(i, j) for j in range(5) ,因此它將轉到函數is_diagonal而沒有看到... for i in range(5)的外部循環。 但是如果這是真的,那么函數is_diagonal似乎將作為輸入變量(0,j)(1,j) ,..., (4,j) ,因此is_diagonal沒有得到足夠的輸入變量(因為未定義j )。 有人可以解釋一下我的思路出了什么問題嗎?

從尤達(Yoda)的意義上講,這種表達(一種理解)幾乎是最好的:倒向是這樣。 表達式的最后一部分在第一個部分之前進行求值。

此功能等效於:

def make_matrix(num_rows, num_cols, entry_fn):
    ret = [] # you are dealing with an outer list 
    # and an outer loop
    for i in range(num_rows):
        cur = [] # and an inner list
        # And an inner loop
        for j in range(num_cols):
            curr.append(entry_fn(i,j)) # you add the result to the inner list
        # and once you're done with the inner loop, and the result to the outer list
        ret.append(cur) 
    # finally, complete the outer loop and return the result
    return ret

i j存在於函數的較大上下文中,即使在壓縮程度更高的i之后定義了j

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM