使用索引的字典理解
Dict comprehension using index
如何使用字典推导得到这段代码的等效结果?
dict_sq = dict()
i = 0
for y in range(grid_height):
for x in range(grid_width):
dict_sq[(x, y)] = i
i = i + 1
{(0, 0): 0, (0, 1): 1, (0, 2): 2, (1, 0): 3, (1, 1): 4, (1, 2): 5, (2, 0): 6, (2, 1): 7, (2, 2): 8}
我使用这种方法获得了相同的结果,但键和值颠倒了:
dict(enumerate((x, y) for y in range(grid_height) for x in range(grid_width)))
但我需要索引作为值而不是键。有一种使用枚举的优雅方法吗?
使用字典理解一次性反转键和值:
>>> {
... (x, y): i
... for i, (x, y)
... in enumerate((x, y) for x in range(grid_height) for y in range(grid_height))
... }
{(0, 0): 0, (0, 1): 1, (0, 2): 2, (1, 0): 3, (1, 1): 4, (1, 2): 5, (2, 0): 6, (2, 1): 7, (2, 2): 8}
这个怎么样?
from itertools import product
d = {(i, j): v for v, (i, j) in enumerate(product(range(grid_height), range(grid_height)))}
如何使用字典推导得到这段代码的等效结果?
dict_sq = dict()
i = 0
for y in range(grid_height):
for x in range(grid_width):
dict_sq[(x, y)] = i
i = i + 1
{(0, 0): 0, (0, 1): 1, (0, 2): 2, (1, 0): 3, (1, 1): 4, (1, 2): 5, (2, 0): 6, (2, 1): 7, (2, 2): 8}
我使用这种方法获得了相同的结果,但键和值颠倒了:
dict(enumerate((x, y) for y in range(grid_height) for x in range(grid_width)))
但我需要索引作为值而不是键。有一种使用枚举的优雅方法吗?
使用字典理解一次性反转键和值:
>>> {
... (x, y): i
... for i, (x, y)
... in enumerate((x, y) for x in range(grid_height) for y in range(grid_height))
... }
{(0, 0): 0, (0, 1): 1, (0, 2): 2, (1, 0): 3, (1, 1): 4, (1, 2): 5, (2, 0): 6, (2, 1): 7, (2, 2): 8}
这个怎么样?
from itertools import product
d = {(i, j): v for v, (i, j) in enumerate(product(range(grid_height), range(grid_height)))}