python-3.x - 自动植物收获算法
问题描述
我正在尝试编写一种算法来指示机械臂收割植物。为了做到这一点,我需要为植物位置创建一个类,该类记录它们在三维空间中的位置以及自该位置上次收获以来的时间。我已经编写了生成字典的代码,该字典为每个植物位置提供一个“代码”(例如 p1、p2、p3 等)以及它在球坐标中的位置(即半径和 phi)。我需要拿这本字典并将每个条目转换为一个类实例。
下面是生成字典的算法。它的格式为 'p1': (10, 1), 'p2': (10, 2), 'p3': (10, 3), 'p4': (20, 1), 'p5': (20, 2) 等。
我需要拿这本字典并为每个条目创建一个“植物”类的实例。下面是植物类。delta_t 是自上次收获以来的时间,将用于确定机械臂是否应该跳过该位置并移动到准备收获的更成熟的植物上,但现在我将该字段留空。
class Plant:
def __init__(self,phi,r,delta_t):
self.r=r
self.phi=phi
self.delta_t=delta_t
所需的格式是:
p1=Plant(10,1)
p2=Plant(10,2)
p3=Plant(10,3)
p4=Plant(20,1)
等等...
我如何在不手动输入每个实例的情况下实现这一点。从 phi 和 r 值以及要收获的植物数量中的所有内容都必须能够随时更改,因此手动将其写出来是没有意义的。
我已经尝试使用 setattr() 以及我可以轻松理解的所有其他解决方案来迭代字典。我是编程新手,所以有很多我不知道的。
#generates an array of phi values
angular_iterations=[]
phi_i=10
phi_f=270
delta_phi=10
for i in range(1,4):
for i in range (phi_i,int(phi_f+delta_phi),delta_phi):
angular_iterations.append(i)
angular_iterations.sort()
print(angular_iterations)
#generates an array of radial values
walkway_width=2
tank_width=2
row_length=3
interplant_disp=1
centrifugal_iterations=[]
while len(centrifugal_iterations)<len(angular_iterations):
for i in range (1,(row_length)+1):
centrifugal_iterations.append(i)
print(centrifugal_iterations)
#combines phi and r to make a 2D array
phi_r=list(zip(angular_iterations,centrifugal_iterations))
print(phi_r)
print("Lists zipped")
#creates a list of plant codes "p"+n where (n) is an integer indicating the harvest order
print("generating plant codes")
plant_codes=[]
length_phi_r=len(phi_r)
while len(plant_codes)<len(phi_r):
for i in range(1,length_phi_r+1):
code="p"+str(i)
plant_codes.append(code)
print(plant_codes)
print("plant codes printed")
print(length_phi_r)
#generates a dictionary using the plant codes and phi_r values
print("generating dictionary")
plant_dictionary={}
zip_code_phir=zip(plant_codes,phi_r)
plant_dictionary=dict(zip_code_phir)
print(plant_dictionary)
print("dictionary generated")
解决方案
您可以使用dictionary comprehension
(文档是关于list comprehensions
但dictionary comprehensions
使用相同的想法):
plant_dictionary = {k: Plant(v[0], v[1]) for k, v in plant_dictionary.items()}
或者,您可以直接设置字典的值:
for key, value in plant_dictionary.items():
plant_dictionary[key] = Plant(value[0], value[1])
推荐阅读
- selenium - Selenium 脚本没有在 Jenkins 上的 Chrome 上运行,但它可以在 eclipse 中运行
- angular - Angular XLSX:包含小数的单元格文本在将 excel 转换为 JSON 对象时给了我一些随机数
- java - 无法使用 Java 流()映射级联列表的字段
- node.js - Next.js 应用程序在创建图像后无法正常工作
- android - 使用 Json Api 的颤振图表
- html - 如何在具有纵横比的 div 中设置居中文本?
- ubuntu - 如何在 Ubuntu Linux 20.04 上安装 kubectx?
- angular - 在子组件上使用 `*ngFor` 比包裹在 `` 在 Chrome 开发工具中
- mysql - 子查询在本地机器上运行良好。但在服务器上没有。为什么?
- python - 使用多重身份验证检查共享点站点的用户凭据