我正在尝试编写一个算法来指示机械臂收割植物。为了做到这一点,我需要为植物位置创建一个类,记录它们在三维空间中的位置以及自该位置上次收获以来的时间。我已经编写了生成字典的代码,该字典为每个工厂位置提供一个“代码”(例如p1、p2、p3等)。以及它在球面坐标中的位置(即半径和φ)。我需要获取这个字典,并将每个条目转换为一个类实例。
下面是生成字典的算法。其格式为'p1':(10,1),'p2':(10,2),'p3':(10,3),'p4':(20,1),'p5':(20,2)等。
我需要使用这个字典,并为每个条目创建"Plant“类的一个实例。下面是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")发布于 2019-09-09 08:52:19
您可以使用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])https://stackoverflow.com/questions/57845315
复制相似问题