我正在尝试将以下代码转换为列表解析以提高紧凑性。谢谢!
grid = {}
for x in range(HOR_SQUARES):
for y in range(VERT_SQUARES):
grid[(x,y)] = GridSquare()
答案 0 :(得分:3)
from itertools import product
grid = {tup: GridSquare() for tup in product(range(HOR_SQUARES), range(VERT_SQUARES))}
如果真的是方形(HOR_SQUARES == VERT_SQUARES
),那么这更简单:
grid = {tup: GridSquare() for tup in product(range(HOR_SQUARES), repeat=2)}
答案 1 :(得分:1)
尝试grid = dict(((x, y), GridSquare()) for x in range(HOR_SQUARES) for y in range(VERT_SQUARES))
答案 2 :(得分:0)
您可以使用字典理解直接转到字典:
grid = {(x, y): GridSquare() for x in range(HOR_SQUARES) for y in range(VERT_SQUARES)}
紧凑性很好但是一旦你的理解开始变得越来越复杂,你可能会 也想格式化它们:
grid = {(x, y): GridSquare()
for x in range(HOR_SQUARES)
for y in range(VERT_SQUARES)}