【发布时间】: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