2016-11-22 46 views
1

好吧,我有一個程序會隨機生成一些元組並將它們添加到列表中以用於製作位圖圖像。 問題是,我不斷收到一個錯誤:Python函數無法識別全局列表

Traceback (most recent call last): File "/Users/Chill/Desktop/Untitled.py", line 27, in <module> 
    nextPixel((pixelList[-1])[0], (pixelList[-1])[1], t,) File "/Users/Chill/Desktop/Untitled.py", line 23, in nextPixel 
    if (i, j) not in pixelList: UnboundLocalError: local variable 'pixelList' referenced before assignment [Finished in 0.078s] 

這裏是代碼:

from random import randint 
from PIL import Image 

startPixel = (0, 0) 
pixelList = [startPixel] 
print(pixelList[-1]) 
print(pixelList[-1][0]) 
i = j = 0 
#Replace 0 with timestamp for seed 
t = 0 


def nextPixel(i, j, t): 
    #Random from seed 
    iNew = i + randint(0, 2) 
    #Random from -seed 
    jNew = j + randint(0, 2) 
    if iNew == jNew: 
     jNew = (jNew + 1) % 2 
    iNew -= 1 
    jNew -= 1 
    #Checks pixel created does not already exist in the list 
    if (iNew, jNew) not in pixelList: 
     pixelList += (iNew, jNew) 

while pixelList[-1][0] < 255: 
    nextPixel((pixelList[-1])[0], (pixelList[-1])[1], t) 

有什麼建議?

+0

你nextPixel函數的開頭添加「全球pixelList」。儘管如此,節目之王通常不被認爲是非常優雅的。 –

回答

0

看起來pixelList是一個元組列表,並且nextPixel函數是爲它添加一個新元組的意思。然而,該行:

pixelList += (iNew, jNew) 

實際上是試圖連擊的新的元組和列表。這是行不通的,因爲擴大賦值將把pixelList當作本地變量(它不存在,導致錯誤)。

你需要做的,而不是這是什麼:

pixelList.append((iNew, jNew))