我似乎无法弄清楚如何获得坚持列表/元组的值之和
我尝试过使用键和其他一些方法,但都无法使用
#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()
我想获取价格的总和,并从该清单中减去最小的金额。
答案 0 :(得分:1)
products = [('a',1),('b',2),('c',30),('d',10),('e',5)]
totalcost = sum([x[1] for x in products]) - min(products, key=lambda x:x[1])[1]
print(totalcost)
答案 1 :(得分:1)
您有几个问题:
您没有数字,只有字符串:
def getInput(): product_name = input("What is the product?") # string product_price = input("What s the price?") # string return (product_name, product_price)
修复(仅是价格输入部分):
while True:
try:
product_price = int(input("What s the price?"))
if product_price <= 0:
raise ValueError
break
except ValueError:
print("Not a valid price")
请参见Asking the user for input until they give a valid response,以了解其他避免ValueError
的方法。
只要您没有数字,'1000'
就会小于'2'
(字母比较)。
您最便宜的商品计算结果不符合预期:
即使您将产品固定为具有编号,您的totalCost
也不起作用:
product[1] # this is the 2nd element of your list - not the price of it 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])
修正(f.e。):
# assumes numbers in ("icecream", 42) - not strings
sortedItems = sorted(products, lambda x:x[1]) # sort by price ascending
minItem = sortedItems[0]
totalCost = sum(item[1] for item in sortedItems[1:]) # don't calc the lowest value
totalCost = sum(products[1]) - min(products[1])
使用min()
也可以,但是通过排序,您可以使用列表切片对除最低点以外的所有部分求和。如果您有巨大列表-min()
更为合适:
minItem = min(products, lambda x:x[1])
total = sum(item[1] for item in products) - minItem[1] # reduced by minItems cost
我修复了代码,以使用提供给函数的参数,而不使用全局参数-也不需要min()产品列表,因为无论如何您都要对其进行排序-您可以简单地切掉最低的项目并扣除其价值:
固定代码和示例输入:
def getInput():
product_name = input("What is the product? ")
while True:
try:
# whole number prices assumed, else use float( input ( ... ))
product_price = int(input("What s the price? "))
if product_price <= 0:
raise ValueError
break
except ValueError:
print("Wrong input - prices must be greater 0 and whole numbers")
return (product_name, product_price)
def showTable(p):
for x in p:
print("Product Name | Price: ", x[0],x[1])
def cheapestItem(p):
# assumes sorted list of items in p
print("The cheapest item in this list is: ", p[-1])
print("Congratulations you get this item free")
#calculate total
totalCost = sum(i[1] for i in p[:-1])
print("Total Cost:", totalCost, "You saved:", p[-1])
products = []
for x in range(5):
product = getInput()
products.append(product)
# sort list - cheapestItem(..) needs a sorted input to work
products.sort(key=lambda t: t[1], reverse=True)
showTable(products)
cheapestItem(products)
输出:
What is the product? apple
What s the price? 22
What is the product? pear
What s the price? 11
What is the product? kiwi
What s the price? 5
What is the product? pineapple
What s the price? no idea
Wrong input - prices must be greater 0 and whole numbers
What s the price? 100
What is the product? gears
What s the price? 1
Product Name | Price: pineapple 100
Product Name | Price: apple 22
Product Name | Price: pear 11
Product Name | Price: kiwi 5
Product Name | Price: gears 1
The cheapest item in this list is: ('gears', 1)
Congratulations you get this item free
Total Cost: 138 You saved: ('gears', 1)
答案 2 :(得分:0)
尝试一下:
#initialise variables
products = []
totalCost = 0.0
#input products and prices funtions
def getInput():
product_name = input("What is the product?")
product_price = int(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(price))
print("Congratulations you get this item free")
price = []
for i in range(len(products)):
price.append(products[i][1])
totalCost = sum(price) - min(price)
print(totalCost)
#main
showTable()
cheapestItem()
您不能将元组列表传递给sum()。它需要一个数字列表。
答案 3 :(得分:-1)
如果我说对了,这应该可以工作:
products.remove(min(products))
print(sum(products))