Python把世界分成垃圾箱

2024-09-30 01:37:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力把移动的球放到合适的箱子里。我想我是在正确的轨道上,但我已经被困了一段时间了。在

我遗漏了一些似乎与我的问题无关的代码,但如果回答者需要进一步的细节,我可以提供给他们。基本上,我有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}$

那么,有人知道如何根据给定的世界坐标将世界划分为垃圾箱吗?我不确定要使用哪种数据结构,因为我不能为键使用元组。提前感谢您的反馈。在


Tags: 方法代码字典世界细节int元组轨道
2条回答

你为什么要字典?你可以这样做,但要记住,你将只有每个箱子得到一个球,因为你是专门把他们的钥匙铸造成(int,int)和钥匙是唯一的。在

如果使用集合,还可以排序(在我的示例中,我按区域标识符排序):

我不知道你为什么这么做,但你可以做到:

import math
import random
import time
import sys


ball_min_radius = 16.0 #world coordinates         
ball_max_radius = 128.0  #world coordniates
number_balls = 200

world_min_x = -200.0*number_balls**.5  # minimum x in world coordinates
world_max_x = +200.0*number_balls**.5  # maximum x in world coordinates
world_min_y = -200.0*number_balls**.5  # minimum y in world coordinates
world_max_y = +200.0*number_balls**.5  # maximum y in world coordinates


class Ball:
    """ 
    Implements a point/ball
    """

    def __init__(self):
          self.x = random.uniform(world_min_x,world_max_x)
          self.y = random.uniform(world_min_y,world_max_y)
          self.radius = int(random.uniform(ball_min_radius,ball_max_radius))
    def __lt__(self, other):
        return self.id < other.id

    def __str__(self):
        return 'x={x} y={y} r={r}'.format(x=self.x, y=self.y, r=self.radius)

def main():

    balls = [Ball() for i in range(number_balls)]

    dict_of_balls = {}
    ball_collection = []
    for b in balls:
        xb = int(b.x/256)
        yb = int(b.y/256)
        key = (xb, yb)
        dict_of_balls[key] = b

        ball_collection.append((key, b))

    print 'length of dictionary:{}'.format(len(dict_of_balls.keys()))
    print 'length of collection:{}'.format(len(ball_collection))

请注意,字典中的条目比集合中的条目少。在

您也可以这样简单地打印每个项目:

^{2}$

或者,根据需要对它们进行排序:

    print 'Collections also let you sort the collection by region(s)...'
    sorted_list = sorted(ball_collection, key= lambda x: (x[0][0], x[0][1]))


    for b in sorted_list:
        print 'ball region: {r}   with coords: {c}'.format(r=b[0], c=b[1])

你也可以很简单地在特定区域获得球:

    print '... or get only ones in a specific region'
    subset =  [b for b in ball_collection if b[0][0] == 1]

    for b in subset:
        print 'ball region: {r}   with coords: {c}'.format(r=b[0], c=b[1])


main()

你似乎在做什么。在

您可以使用元组作为字典中的键,因为元组是不可变的。唯一不能用于字典键的数据类型是列表[]或集合{}

**a = {(1,2):'example1', (2,3):'example2'}
>>> a[(1,2)]
'example1'**

所以我相信这会使你的问题更容易解决。在

相关问题 更多 >

    热门问题