Python 将两个列表中的值相乘并打印出来
我正在努力做到这一点,这样我就可以将每个成本乘以相应的销售产品数量。例如,1.99*10、1.49*5等。此外,我似乎不知道如何根据列表中的成本打印出最昂贵或最便宜产品的产品名称。我试着将产品成本中的I乘以售出产品的相应I,但答案似乎相去甚远。有人知道如何解决这个问题吗?谢谢 但是,使用下面的代码Python 将两个列表中的值相乘并打印出来,python,list,python-3.x,function,Python,List,Python 3.x,Function,我正在努力做到这一点,这样我就可以将每个成本乘以相应的销售产品数量。例如,1.99*10、1.49*5等。此外,我似乎不知道如何根据列表中的成本打印出最昂贵或最便宜产品的产品名称。我试着将产品成本中的I乘以售出产品的相应I,但答案似乎相去甚远。有人知道如何解决这个问题吗?谢谢 但是,使用下面的代码 # product lists product_names = ["prime numbers", "multiplication tables", "mortgage calculator"] pr
# product lists
product_names = ["prime numbers", "multiplication tables", "mortgage calculator"]
product_costs = [1.99, 1.49, 2.49]
product_sold = [10, 5, 15]
def report_product():
total = 0
print("Most expensive product:", max(product_costs))
print("Least expensive product:", min(product_costs))
for i in range(len(product_costs)):
total += i * product_sold[i]
print("Total value of all products:", total)
selection = ""
while selection != "q":
selection = input("(s)earch, (l)ist, (a)dd, (r)emove, (u)pdate, r(e)port or (q)uit: ")
if selection == 'q':
break
elif selection == 's':
search_product()
elif selection == "l":
list_products()
elif selection == "a":
add_products()
elif selection == "r":
remove_products()
elif selection == "u":
update_products()
elif selection == "e":
report_product()
else:
print("Invalid option, try again")
print("Thanks for looking at my programs!")
要获得相应索引的新数组,请乘以
product_costs = [1.99, 1.49, 2.49]
product_sold = [10, 5, 15]
product_mult = list(map(lambda x,y: x*y, product_costs,product_sold))
要找到最贵的产品名称
index = product_costs.index(max(product_costs))
most_expensive = product_names[index]
虽然不一定是最优的,但您可以使用
zip()
以最少的代码获得答案:
输出
Most expensive product: mortgage calculator
Least expensive product: multiplication tables
Total earned from all products sold: $64.70
还可以使用numpy将两个列表相乘
>>> import numpy
>>> list(numpy.array(product_costs)*numpy.array(product_sold))
[19.899999999999999, 7.4500000000000002, 37.350000000000001]
非主题:
if selection='q':break
是冗余的,因为while循环的条件是while selection!='q'
无论如何都要打破循环扫描你显示搜索产品、列出产品、删除产品、更新产品、报告产品功能的代码。[x*y代表产品中的x,y代表已售出产品中的y]生成所有九种可能的产品:[19.9,9.95,29.85,14.9,7.45,22.35,24.90000000000002,12.450000000000001,37.35]
不是OP要找的三个。codeindex=product\u mult.index(max(product\u mult))
找到赚得最多的产品,不一定是最贵的产品。哦,糟糕,误读了问题!再次感谢您的关注,在回答问题时必须更加清晰:/
>>> prod_m = [a*b for a,b in zip(product_costs, product_sold)]
>>> prod_m
[19.9, 7.45, 37.35]
>>> product_names[product_costs.index(max(product_costs))]
'mortgage calculator'
>>> product_names[product_costs.index(min(product_costs))]
'multiplication tables'
>>> import numpy
>>> list(numpy.array(product_costs)*numpy.array(product_sold))
[19.899999999999999, 7.4500000000000002, 37.350000000000001]