假设我有机器人,其位置由笛卡儿轴系统上的一对整数坐标表示。
也就是说,机器人列表的位置如下所示:
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_list添加到robots_positions列表中,以获得每个机器人的新位置。
因此,在我们的例子中,期望的结果是:
robots_positions + moves_list = [[2, 14], [2, 13], [2, 7], [3, 14]] 我怎么能轻易做到呢?
我想做的是:
np.power(len(robots_positions), 5)
发布于 2020-12-03 16:49:00
您可以根据运动方向使用一组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_positions和moves_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]]发布于 2020-12-03 16:31:40
以下是代码:
def movement(robots_positions,moves_list):
for i in range(len(robots_positions)):
if moves_list[i]=="up":
robots_positions[i][1]=robots_positions[i][1]+1
elif moves_list[i]=="down":
robots_positions[i][1]=robots_positions[i][1]-1
elif moves_list[i]=="left":
robots_positions[i][0]=robots_positions[i][0]-1
elif moves_list[i]=="right":
robots_positions[i][0]=robots_positions[i][0]+1
elif moves_list[i]=="stay":
pass
else:
print('Invalid command in list')
return robots_positions
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.
print(movement(robots_positions,moves_list))https://stackoverflow.com/questions/65129932
复制相似问题