【问题标题】:Automated Plant Harvesting Algorithm自动植物收获算法
【发布时间】:2019-09-08 19:57:09
【问题描述】:

我正在尝试编写一种算法来指示机械臂收割植物。为了做到这一点,我需要为植物位置创建一个类,该类记录它们在三维空间中的位置以及自该位置上次收获以来的时间。我已经编写了生成字典的代码,该字典为每个植物位置提供“代码”(例如 p1、p2、p3 等)以及它在球坐标中的位置(即半径和 phi)。我需要拿这本字典并将每个条目转换为一个类实例。

以下是生成字典的算法。它的格式为 'p1': (10, 1), 'p2': (10, 2), 'p3': (10, 3), 'p4': (20, 1), 'p5': (20, 2) 等

我需要使用这本字典并为每个条目创建一个“Plant”类的实例。下面是植物类。 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")

【问题讨论】:

    标签: python-3.x class dictionary


    【解决方案1】:

    您可以使用dictionary comprehension(文档是关于list comprehensionsdictionary 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])
    

    【讨论】:

    • 谢谢!我以前见过这个,但它没有注册为解决方案。我会试试这个,然后就结果回复你。
    • 已经取得了好的进展,但是当我尝试检索条目的值时:print(p1.phi) 我收到错误“NameError: name 'p1' is not defined”。你知道我会怎么解决这个问题吗?感谢您的帮助。
    • 您应该访问字典中的值:plant_dictionary['p1'].phi
    猜你喜欢
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 2012-10-08
    • 2020-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多