在Python中,在包含字符串和浮点数的列表中查找最小值的最简单方法是什么?

时间:2013-05-10 03:30:27

标签: python python-3.x

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

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

2 个答案:

答案 0 :(得分: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现在将是我上面描述的元组列表。

答案 1 :(得分:1)

将您的products分为三个以取消它:

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

然后拿下分钟......

recommended = min(grouped, key=lambda (name, qty, price): float(price) / int (qty))[0]