列表/元组槽中值的总和

2024-10-17 02:28:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我似乎不知道如何得到列表/元组中的值之和

我试过使用键和其他一些方法,但都不管用

#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()

我想得到价格的总和,然后从清单中减去最小的金额。你知道吗


Tags: thenameinforinputisdefproduct
3条回答

您有几个问题:

您没有数字,只有字符串:

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)
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)

试试这个:

#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()。它需要一个数字列表。你知道吗

相关问题 更多 >