如何将此循环转换为列表解析?

时间:2014-10-14 01:34:21

标签: python dictionary

我正在尝试将以下代码转换为列表解析以提高紧凑性。谢谢!

grid = {}
for x in range(HOR_SQUARES):
    for y in range(VERT_SQUARES):
        grid[(x,y)] = GridSquare()

3 个答案:

答案 0 :(得分:3)

itertools.product很不错:

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)}