首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >植物自动收获算法

植物自动收获算法
EN

Stack Overflow用户
提问于 2019-09-09 03:57:09
回答 1查看 47关注 0票数 1

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

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

我需要使用这个字典,并为每个条目创建"Plant“类的一个实例。下面是Plant类。delta_t是自上次收获以来的时间,它将用于确定机械臂是否应该跳过该位置,转移到准备收获的更成熟的植物上,但现在我将该字段留空。

代码语言:javascript
运行
复制
class Plant:
    def __init__(self,phi,r,delta_t):
        self.r=r
        self.phi=phi
        self.delta_t=delta_t

所需的格式为:

代码语言:javascript
运行
复制
p1=Plant(10,1)
p2=Plant(10,2)
p3=Plant(10,3)
p4=Plant(20,1)

以此类推。

如何在不手动键入每个实例的情况下实现这一点。从phi和r值以及要收获的植物数量的所有内容都必须能够随时更改,因此手动将其写入没有意义。

我已经尝试使用setattr()遍历字典,以及我可以理解的所有其他解决方案。我是编程新手,所以有很多我不知道的东西。

代码语言:javascript
运行
复制
#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")
EN

回答 1

Stack Overflow用户

发布于 2019-09-09 08:52:19

您可以使用dictionary comprehension (文档是关于list comprehensions的,但dictionary comprehensions使用相同的概念):

代码语言:javascript
运行
复制
plant_dictionary = {k: Plant(v[0], v[1]) for k, v in plant_dictionary.items()}

或者,您可以直接设置字典的值:

代码语言:javascript
运行
复制
for key, value in plant_dictionary.items():
    plant_dictionary[key] = Plant(value[0], value[1])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57845315

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档