我正在努力把移动的球放到合适的箱子里。我想我是在正确的轨道上,但我已经被困了一段时间了。在
我遗漏了一些似乎与我的问题无关的代码,但如果回答者需要进一步的细节,我可以提供给他们。基本上,我有200个移动球的世界。它们有一个X和Y坐标。我想把世界分成256宽的正方形箱子,然后把球放在适当的箱子里。在
我的方法就是把它们放进字典里。看起来像这样:
dict_of_balls = {}
for i in range(len(balls)):
xb = int(balls[i].x/256)
yb = int(balls[i].y/256)
我想把键变成(xb, yb)
对的元组,然后把适当的球放在那个箱子里,但我不认为你可以用元组作为键。。。在
代码如下:
^{pr2}$那么,有人知道如何根据给定的世界坐标将世界划分为垃圾箱吗?我不确定要使用哪种数据结构,因为我不能为键使用元组。提前感谢您的反馈。在
你为什么要字典?你可以这样做,但要记住,你将只有每个箱子得到一个球,因为你是专门把他们的钥匙铸造成(int,int)和钥匙是唯一的。在
如果使用集合,还可以排序(在我的示例中,我按区域标识符排序):
我不知道你为什么这么做,但你可以做到:
请注意,字典中的条目比集合中的条目少。在
您也可以这样简单地打印每个项目:
^{2}$或者,根据需要对它们进行排序:
你也可以很简单地在特定区域获得球:
你似乎在做什么。在
您可以使用元组作为字典中的键,因为元组是不可变的。唯一不能用于字典键的数据类型是列表
[]
或集合{}
所以我相信这会使你的问题更容易解决。在
相关问题 更多 >
编程相关推荐