首页 > 解决方案 > 如何随时移动单位大小的机器人列表?

问题描述

假设我有机器人,其位置由笛卡尔坐标系上的一对整数坐标表示。

也就是说,机器人列表的位置如下所示:

robots_positions = [[2, 13], [2, 12], [2, 8], [3, 14]] 

现在,我想为每个机器人随机生成单位大小的移动(上、下、右、左、原地不动),不受约束。就像是:

moves_list = ["up", "up", "down", "stay"] # Each movement corresponds to one robot from the list above.

接下来,我想将 添加moves_listrobots_positions列表中以获取每个机器人的新位置。

所以在我们的例子中,期望的结果是:

robots_positions + moves_list = [[2, 14], [2, 13], [2, 7], [3, 14]] 

我怎样才能轻松做到这一点?

我想做的是:

  1. 我画了一个数字,即机器人数量的五次方:

    np.power(len(robots_positions), 5)

  2. 我试图将数字移动到以五为底,然后将每个数字视为代表其中一个机器人的运动方向。我已经卡在这里了...

标签: pythonlistnumpy

解决方案


您可以根据运动方向使用一堆if-elif来添加不同的东西,或者您可以简单地使用字典来告诉您每个方向会导致什么变化。例如,

directions = {"up": [0, 1], "down": [0, -1], "left": [-1, 0], "right": [1, 0], "stay": [0, 0]}

robots_positions = [[2, 13], [2, 12], [2, 8], [3, 14]] 
moves_list = ["up", "up", "down", "stay"]

然后,您可以使用zip迭代两者robots_positionsmoves_list一起,从directions字典中获取增量,并将其添加到当前位置

for robot_num, (pos, move) in enumerate(zip(robots_positions, moves_list)):
    delta = directions.get(move, [0, 0]) # If move doesn't exist, do nothing
    new_pos = [p + d for p, d in zip(pos, delta)]
    robots_positions[robot_num] = new_pos

或者,作为列表理解:

robots_positions = [ [p + d for p, d in zip(pos, directions.get(move, [0, 0]))] for pos, move in zip(robots_positions, moves_list)]

现在我们有了新的职位:

[[2, 14], [2, 13], [2, 7], [3, 14]]

推荐阅读