Python函数无法识别全局lis

2024-09-29 01:36:08 发布

您现在位置: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)

有什么建议吗?你知道吗


Tags: infromifnotusersfileseedrandint
1条回答
网友
1楼 · 发布于 2024-09-29 01:36:08

似乎pixelList是一个元组列表,而nextPixel函数意味着向它附加一个新元组。但是,行:

    pixelList += (iNew, jNew)

实际上是试图连接新元组和列表。这将不起作用,因为未赋值的赋值将pixelList视为局部变量(该变量不存在,导致错误)。你知道吗

你需要做的是:

    pixelList.append((iNew, jNew))

相关问题 更多 >