python - 如何随时移动单位大小的机器人列表?
问题描述
假设我有机器人,其位置由笛卡尔坐标系上的一对整数坐标表示。
也就是说,机器人列表的位置如下所示:
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)
我试图将数字移动到以五为底,然后将每个数字视为代表其中一个机器人的运动方向。我已经卡在这里了...
解决方案
您可以根据运动方向使用一堆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]]
推荐阅读
- c# - 如何使用 C#.NET 类/DLL 创建 C++ DLL
- java - 在每个间隔后更改帧的显示,就像动画一样
- android - Handler() 已弃用
- docker - docker sed arg 变量没有被使用
- reactjs - 出现错误:找到以下环境的绑定:-在我的 ubuntu 系统中使用 Node.js 9.x 的 Linux 64 位
- mysql - 在用户输入之前匹配特定字符串
- node.js - 使用 Nextjs 应用程序空闲 1 分钟后 Openlitespeed 会话超时
- javascript - 这个 Buefy (Vue + Bulma) 函数在这里做什么?
- java - 排序无法正常工作!Java 排序
- python-3.x - 为什么 PIL 无法显示图像并显示错误“在“文件:///tmp/tmp .....PNG”中找不到图像