尝试为4x4电路板坐标创建python字典

时间:2018-10-03 16:28:15

标签: python dictionary

我想要所需的输出为-

coord = {0: (0, 0), 1: (0, 1), 2: (0, 2), 3: (0, 3), 4: (1, 0), 5: (1, 1), 6: (1, 2), 7: (1, 3),8: (2, 0), 9: (2, 1), 10: (2, 2), 11: (2, 3),12: (3, 0), 13: (3, 1), 14: (3, 2), 15: (3, 3)}

使用

coord = {}

for i in range(0,16):

    if i < 4:
        for j in range (0,4):
            coord[i] = (0,j)
    elif   i > 3 and i <8:
        for j in range (0,4):
            coord[i] = (1,j)
    elif i > 7 and i < 12:
        for j in range (0,4):
            coord[i] = (1,j)
    elif i > 11 and i < 16:
        for j in range (0,4):
            coord[i] = (1,j)
print (coord)

将输出作为 {0: (0, 3), 1: (0, 3), 2: (0, 3), 3: (0, 3), 4: (1, 3), 5: (1, 3), 6: (1, 3), 7: (1, 3), 8: (1, 3), 9: (1, 3), 10: (1, 3), 11: (1, 3), 12: (1, 3), 13: (1, 3), 14: (1, 3), 15: (1, 3)}

无法构建逻辑以获得所需的输出。

2 个答案:

答案 0 :(得分:3)

最直接的方法是使用嵌套的for循环。

k = 0
d = {}
for i in range(4):
     for j in range(4):
         d[k] = (i, j)
         k += 1

或者,如果您更喜欢单线,则加倍理解

 dict( enumerate ( [ (i, j) for i in range(4) for j in range(4)] )) 

要使循环或理解简单,我们可以使用整数算术运算符// //(整数除法)和%余数

 { k : (k // 4, k % 4) for k in range(16) }

这可能更优雅,更快捷

答案 1 :(得分:0)

我们可以用Cartesian product来枚举itertools.product的整数。

import itertools as it


{i: x for i, x in enumerate(it.product(range(3+1), repeat=2))}
# {0: (0, 0),
#  1: (0, 1),
#  2: (0, 2),
#  3: (0, 3),
#  ...
#  15: (3, 3)}