字典值不会保持恒定

时间:2018-10-29 11:52:50

标签: python

当键“ 0”被填充时,最终值不同于单个键填充时的值

{0: (0, 0), 1: (1, 0), 2: (2, 0), 3: (3, 0), 4: (4, 0),
 5: (5, 0), 6: (6, 0), 7: (7, 0), 8: (8, 0), 9: (9, 0),
 10: (10, 0), 11: (11, 0), 12: (12, 0)

等;一旦外部while循环完全完成,这些值就会更改。他们变成:

{0: (0, 0), 1: (0, 0), 2: (-1, 0), 3: (-2, 0), 4: (-3, 0), 
 5: (-4, 0), 6: (-5, 0), 7: (-6, 0), 8: (-7, 0), 9: (-8, 0), 
 10: (-9, 0), 11: (-10, 0), 12: (-11, 0)

我不知道为什么。任何帮助深表感谢。您可以取消注释打印语句以供参考。

代码:

import numpy as np
from math import cos,sin,pi

ANGLE_ACCURACY = 0.5

noOfAnglesLimit = (360.0/ANGLE_ACCURACY)*0.5
angle = 0

polarLut = dict()
inner = dict()

while angle<noOfAnglesLimit:
    theta = (pi/180.0)*(angle*ANGLE_ACCURACY)

    radius = 0
    while radius<=200:
        x = int(float(radius)*cos(theta)+0.5)
        y = int(float(radius)*sin(theta)+0.5)
        inner[radius] = (x,y)
        radius+=1        

    polarLut[angle] = inner
    #print(polarLut)
    angle+=1

import json

with open('file.txt', 'w') as file:
     file.write(json.dumps(polarLut))

2 个答案:

答案 0 :(得分:3)

您只有一个inner字典,您将其分配给polarLut字典的所有值,然后再次为下一个angle对其进行修改。

您想要的东西

polarLut = dict()

while angle < noOfAnglesLimit:
    theta = (pi / 180.0) * (
        angle * ANGLE_ACCURACY
    )
    inner = dict()
    radius = 0
    while radius <= 200:
        x = int(float(radius) * cos(theta) + 0.5)
        y = int(float(radius) * sin(theta) + 0.5)
        inner[radius] = (x, y)
        radius += 1

    polarLut[angle] = inner
    angle += 1

相反。

此外,我建议改用for angle in range(noOfAnglesLimit),它更像Python。

答案 1 :(得分:1)

您始终在polarLut中存储相同的词典,因此所有条目都指向相同的原始inner

在您的while循环内移动inner的声明。