gpt4 book ai didi

python - 在 Python 中,在包含字符串和 float 的列表中找到最小值的最简单方法是什么?

转载 作者:太空宇宙 更新时间:2023-11-04 10:47:10 25 4
gpt4 key购买 nike

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

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

最佳答案

我建议不要将所有 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 现在将是我上面描述的元组列表。

关于python - 在 Python 中,在包含字符串和 float 的列表中找到最小值的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16474735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com