向python列表的元素添加值时的奇怪行为

时间:2018-08-07 18:30:52

标签: python-3.x

我正在尝试创建一个游戏,该游戏会从一组游戏中随机选择一个“房间”布局,然后将其放在屏幕上4个位置中的1个位置。我实现此目的的代码是:

#read csv from HDFS to a pandas df 
conf = SparkConf().setAppName("Read_CSV")
sqlContext = sql.SQLContext(sc)
df = sqlContext.read.csv("hdfs://localhost:9000/density/output/*", 
header=True, sep=",").toDF("x", "y", "d").toPandas()

def tuples(a): 
    return (a, a, a)

#lerps the density to a gray scale color
df['d'] = (df['d'] / 600 * 255).astype(int)
df['d'] = df['d'].apply(tuples)

#creates a 501 * 501 white image
img = Image.new( 'RGB', (501,501), "white")
pixels = img.load()

#goes through the df and colors the pixels
for i in range(len(df['x'])): 
    pixels[df['x'][i], df['y'][i]] = df['d'][i]
imgplot = plt.imshow(img, origin='lower', vmin=0, vmax=600)

但是,每当选择与先前选择的房间相同的房间时,其值都会多次增加修改值,因此不会出现在屏幕上。谁能解释为什么会这样,以及如何解决。

编辑:经过进一步的研究和调试,由于某种原因,当将修饰符值添加到these_segments和these_shapes时,该相同值也会添加到段和形状中已经存在的相同值中,如here所示。似乎room_2_segments本身的值已被修改。有人知道这是为什么以及如何预防?

1 个答案:

答案 0 :(得分:0)

请注意,room_spawns是一个长度为1(包含一个布尔值)的列表。因此,room_spawns[0]将返回该布尔值,但是对于i> 0,您将得到一个IndexError

另外,请注意[randint(0, 5)] in range(4)总是返回False,因为[randint(0,5)]不是整数,它是一个只有一个元素的列表。而且由于room_spawns是具有此布尔值的列表,所以它将始终等于[False]

也许您希望room_spawns是包含多个元素的列表?