我正在尝试做一个类似程序的商店,有5种商品,它询问您产品的名称和价格,我想按价格降序进行组织。
#initialise variables
product1 = []
product2 = []
product3 = []
product4 = []
product5 = []
products = []
totalCost = 0.0
#input products and prices funtions
def getInput1():
product1.append(input("What is the product?"))
product1.append(input("What is the price?"))
def getInput2():
product2.append(input("What is the product?"))
product2.append(input("What is the price?"))
def getInput3():
product3.append(input("What is the product?"))
product3.append(input("What is the price?"))
def getInput4():
product4.append(input("What is the product?"))
product4.append(input("What is the price?"))
def getInput5():
product5.append(input("What is the product?"))
product5.append(input("What is the price?"))
#ask user products and prices
getInput1()
getInput2()
getInput3()
getInput4()
getInput5()
products.append([product1, product2, product3, product4, product5])
products.sort(key=lambda tup: tup[1], reverse = True)
print("List is in format Product Name | Price")
print(products)
它只是正常显示价格,没有排序 (p.s)我知道这可能会更整洁,但我对方法一无所知
答案 0 :(得分:3)
问题在于$('table').tablesorter({
sortList: [[0, 1], [2, 0]]
});
是您在其中插入另一个列表products
的列表。然后,您将对外部列表(一个元素-内部列表)进行排序,而这些列表当然保持不变。
您可以改用[product1, product2, product3, product4, product5]
来代替products = [product1, product2, product3, product4, product5]
,一切都会按预期进行。
为进行清理,为什么要具有所有这些单独的功能?只需编写一个products.append(...)
函数。
get_product
然后收集其中的5个:
def get_product():
productname = input("What is the product? ")
productprice = input("What is the price? ")
return (productname, productprice)
并排序
products = []
for _ in range(5): # this is an idiomatic way to run the code in the for loop 5 times
product = get_product()
products.append(product)