我有一个数据库表,其中每一行都有:
name,
child1,
child1_quantity,
child2,
child2_quantity,
child3,
child3_quantity,
price此表将作为字典列表或字典字典(无关紧要)引入到python中。它看起来像这样:
[{name: A, child1: C1, child1_quantity:2, child2:C2, child2_quantity: 1, child3: C3, child3_quantity:3, price: null},
{name: C1, child1: C1A, child1_quantity:5, child2: C1B, child2_quantity:2, child3: C1C, child3_quantity:6, price: 3},
{name: C2, child1: C2A, child1_quantity:5, child2: C2B, child2_quantity:2, child3: C2C, child3_quantity:10, price: 4},
{name: C3, child1: C3A, child1_quantity:3, child2: C3B, child2_quantity:7, child3: C3C, child3_quantity:15, price: null}]问题案例:我希望能够输入组件的名称并获得其价格。如果表中给出了价格,那么简单地返回它。如果没有给出价格,我们必须通过将其子代的价格相加来计算价格。
(child1 price x child1 qty) + (child2 price x child2 qty) + .....但每个孩子可能/可能没有价格。因此,我们需要从孩子的孩子那里找到孩子的总成本,然后把它带上来……直到我们得到孩子的总价格,然后将它们相加,得到我们感兴趣的部分的价格。这是一个递归类型的问题,我想,但我不能考虑如何概念化或表示数据来使我的目标成为可能。我能得到一些线索/提示吗?sql递归查询不是一个选项。我正尝试在python数据结构或对象中做到这一点。谢谢。
发布于 2016-09-14 06:14:34
def find_price(self, name):
if self.dictionary[name]["price"]:
return self.dictionary[name]["price"]
else:
#assuming this is in a class...otherwise use global instead of self
return self.find_price(dictionary[name]["child1"])*dictionary[name]["child1_quantity"] + find_price(self.dictionary[name]["child2"])*self.dictionary[name]["child2_quantity"]#.....etc这还假设您读取数据的顶级对象是一种术语,其中除了名称字段之外,名称还充当关键字。
https://stackoverflow.com/questions/39479335
复制相似问题