我似乎不知道如何得到列表/元组中的值之和
我试过使用键和其他一些方法,但都不管用
#initialise variables
products = []
totalCost = 0.0
#input products and prices funtions
def getInput():
product_name = input("What is the product?")
product_price = input("What s the price?")
return (product_name, product_price)
#collect input
for x in range(5):
product = getInput()
products.append(product)
#sort list
products.sort(key=lambda t: t[1], reverse=True)
#show list
def showTable():
for x in range(5):
print("Product Name | Price: ", products[x])
#calculate cheapest
def cheapestItem():
print("The cheapest item in this list is: ", min(products, key = lambda t: t[1]))
print("Congratulations you get this item free")
#calculate total
totalCost = sum(products[1]) - min(products[1])
#main
showTable()
cheapestItem()
我想得到价格的总和,然后从清单中减去最小的金额。你知道吗
您有几个问题:
您没有数字,只有字符串:
修正(只是价格输入部分):
请参阅Asking the user for input until they give a valid response以了解如何避免
ValueError
的其他方法只要没有数字,
'1000'
就会小于'2'
(按字母顺序比较)。你知道吗您最便宜的项目计算并不能完成它应该做的事情:
即使您将产品固定为有数字,您的
totalCost
也不起作用:固定(f.e.):
使用
min()
也可以,但是通过排序,您可以使用列表切片对除最低值之外的所有值求和。如果您有庞大的列表-min()
更为理想:我将代码固定为使用提供给函数的参数,而不是全局参数-也不需要min()产品列表,因为您可以对其进行排序-您只需切掉最低的项并扣除其值:
固定代码和示例输入:
输出:
试试这个:
不能将元组列表传递给sum()。它需要一个数字列表。你知道吗
相关问题 更多 >
编程相关推荐