1

我的代码要求提供产品列表或从文件中加载它们。然后,我需要找出哪个值是最小的,如果有同样小的元素,选择一个随机的。但是,我仍然需要将该值链接到其相关字符串。到目前为止,我有:

def checkPrices(products):

    for x in range(len(products)):
        if (x)%3 == 0:
            name = str(products[x])
            print(name)
        elif (x+1)%3 == 0:
            quantity = int(products[x])
            print(quantity)
            pricePerUnit = str(format(price/quantity, '.2f'))
            print(name + " is $" + pricePerUnit + " per unit")

        elif (x)%1 == 0:
                price = float(products[x])
                print(price)

我怎样才能扩展它,以便我可以找到每单位的最低价格,然后打印如下内容:

I would recommend product1
4

2 回答 2

3

我建议不要将所有 3 个值都存储在一个平面列表中,就像您似乎...

["product1", "3", "0.15", "product2", "4", "0.40"]

...您改为将它们存储为元组列表:

[("product1", 3, 0.15), ("product2", 4, 0.40)]

这样可以保持每个项目的逻辑分组,并让您执行以下操作...

product_info = [("product1", 3, 0.15), ("product2", 4, 0.40)]
cheapest_product = min(product_info, key=lambda product: product[2] / product[1])

product_name, quantity, total_price = cheapest_product
print "I would recommend %s" % product_name

注意:如果您只有该平面列表并且您想将其转换为元组列表...

products = ["product1", "3", "0.15", "product2", "4", "0.40"]
products_iter = iter(products)
product_tuples = zip(products_iter, products_iter, products_iter)
product_info = [(i[0], int(i[1]), float(i[2]) for i in product_tuples]

现在product_info将是我上面描述的元组列表。

于 2013-05-10T03:41:53.193 回答
1

将你products分成三组以展开它:

grouped = zip (*[iter(products)] * 3)

然后取最小...

recommended = min(grouped, key=lambda (name, qty, price): float(price) / int (qty))[0] 
于 2013-05-10T06:29:07.283 回答