我已经找过其他类似的案例,但没有一个适用于我......或者如果他们这样做我不明白怎么做。
我要做的是过滤2D数组(这个):
blocks = [
[ [0], [0], [0], [0], [0], [0], [0], [0], [0], [0] ],
[ [0], [0], [0], [0], [0], [0], [0], [0], [0], [0] ],
[ [0], [0], [0], [0], [0], [0], [0], [0], [0], [0] ],
[ [0], [0], [0], [0], [0], [0], [0], [0], [0], [0] ],
[ [0], [0], [0], [0], [0], [0], [0], [0], [0], [0] ],
[ [0], [0], [0], [0], [0], [0], [0], [0], [0], [0] ],
[ [0], [0], [0], [0], [0], [0], [0], [0], [0], [0] ],
[ [0], [0], [0], [0], [0], [0], [0], [0], [0], [0] ],
[ [0], [0], [0], [0], [0], [0], [0], [0], [0], [0] ],
[ [0], [0], [0], [0], [0], [0], [0], [0], [0], [0] ]
并找出当前部分是什么。对不起,如果我的代码有点草率,我是python的新手。这是我的代码的一部分,
def drawBlock():
for blockL1 in blocks:
for blokL2 in blocks:
if blocks[blockL1[blockL2[1]]] == 0:
pygame.draw.rect(screen, (0, 255, 255), Rect((blockL1 * 32, blockL2 *32), (32, 32)))
pygame.draw.rect(screen, color, Rect(i * 32, ))
global blockL2
blockL2 += 1
global blockL1
blockL1 += 1
答案 0 :(得分:0)
你在这里遇到了几个问题。
主要问题是您使用for blank in blank_holder
。
写作时
for blockL1 in blocks:
与写作几乎相同
for ii in range(len(blocks)):
blockL1 = blocks[ii]
...
意味着blockL1不是整数,也不是块的索引..它是块的元素!
其值如下:[ [0], [0], [0], [0], [0], [0], [0], [0], [0], [0] ]
哪个列表是列表...其中blocks
是包含列表的列表列表...是的
当你写
for blockL1 in blocks:
for blockL2 in blocks:
blockL2
的值将是单个列表[0]
假设您要查看blockL2
中包含的一个值,您可以更改:
if blocks[blockL1[blockL2[1]]] == 0:
为:
if blockL2[0] == 0: # the 1 index would go out of bounds for a list length 1
但是,此代码看起来需要blockL1
和blockL2
的索引值,因此我建议您循环浏览其索引列表(意为ints
)...而不是它们的元素
def drawBlock():
for blockL1 in range(len(blocks)):
for blockL2 in range(len(blockL1)):
if blocks[blockL1[blockL2[0]]] == 0:
pygame.draw.rect(screen, (0, 255, 255), Rect((blockL1 * 32, blockL2 *32), (32, 32)))
希望这有助于一些人!