我有一本字典velocity
。在字典中訪問字典值
velocity = {"x": ({"mag": 5}, {"dir", 1}), "y": ({"mag": 5}, {"dir", 1})}
我試圖內"x"
訪問"mag"
和"dir"
值。
這是我想做到這一點:
self.position["x"] += (self.velocity["x"]["mag"] * self.velocity["x"]["dir"])
我應該怎樣做呢?
我有一本字典velocity
。在字典中訪問字典值
velocity = {"x": ({"mag": 5}, {"dir", 1}), "y": ({"mag": 5}, {"dir", 1})}
我試圖內"x"
訪問"mag"
和"dir"
值。
這是我想做到這一點:
self.position["x"] += (self.velocity["x"]["mag"] * self.velocity["x"]["dir"])
我應該怎樣做呢?
我認爲你可能要定義爲速度:
velocity = {"x":{"mag": 5, "dir": 1}, "y": {"mag": 5, "dir": 1} }
這樣,你的賦值語句將工作:
position["x"] += (velocity["x"]["mag"] * velocity["x"]["dir"])
的x
和y
鍵的值的元組,而不是類型的字典,所以你需要使用的元組索引來訪問它們:
所以,你的任務應該是:
self.position["x"] += (self.velocity["x"][0]["mag"] * self.velocity["x"][0]["dir"])
爲了使它更直接,使velocity
一個字典:
{'x': {'mag': 5, 'dir': 1}, 'y': {'mag': 5, 'dir': 1}}
這不是在字典詞典。 –