2014-10-27 158 views
-1

在我的代碼中,我試圖通過變量分割嵌套列表中的第二行。這工作正常,但它要求列表上的每個項目的變量,而不是一次。Python:返回函數的列表操作

這是我的代碼有:

nlist = [ 
    [1, 2, 3, 4], 
    [5, 6, 7, 8], 
    [9, 10, 11, 12], 
] 

def divide(): 
    x = int(input('what is your divider?:')) 
    return x 

nlist[1] = [num/divide() for num in nlist[1]] 
print(nlist) 

輸出:

what is your divider?:5 
what is your divider?:5 
what is your divider?:5 
what is your divider?:5 
[[1, 2, 3, 4], [1.0, 1.2, 1.4, 1.6], [9, 10, 11, 12]] 

我所要的輸出是什麼:

what is your divider?:5 
[[1, 2, 3, 4], [1.0, 1.2, 1.4, 1.6], [9, 10, 11, 12]] 

回答

3
nlist[1] = [num/divide() for num in nlist[1]] 

divide()每次叫。使用

divide_value = divide() 
nlist[1] = [num/divide_value for num in nlist[1]] 

只能調用一次並存儲它。