“编写一个程序,提示用户输入5个项目及其价格。然后程序应该从最高价格到最低价格对输入进行排序,并输出显示项目和价格的排序数据。”
这是我到目前为止所做的,我不知道在此之后该怎么做,如果用户只是输入价格,我会没事的,但项目名称也必须输出:
print("Welcome To Shopping List!")
item1 = raw_input('Enter First Item')
item1price = int("Enter First Item Price: ")
item2 = raw_input(input('Enter First Item'))
item2price = int(input("Enter Second Item Price: "))
item3 = raw_input('Enter First Item')
item3price = int(input("Enter Third Item Price: "))
item4 = raw_input('Enter First Item')
item4price = int(input("Enter Fourth Item Price: "))
item5 = raw_input('Enter First Item')
item5price = int(input("Enter Fifth Item Price: "))
data = [(item1, item1price), (item2, item2price), (item3, item3price), (item4, item4price)]
data = [int(x) for x in data]
data.sort()
输出需要如下所示,按最高价格排序:
Coffee 4.99
Kitchen
Towel 1.75
Butter 1.70
Milk 0.45
我是python的新手,所以任何帮助都会非常感激!
答案 0 :(得分:0)
不要为您的商品和价格制作10个或更多变量,而是询问用户他/她想要多少。使用该数字循环并将输入存储在元组中,然后附加到列表中。再次使用'for'
循环显示您的数据。
#!/usr/bin/env python3.6
# Write a program to prompt the user to enter a number of items and their prices.
# The program should then sort the input from highest to lowest price and
# output the sorted data showing the item and the price.
print("Welcome To Shopping List!")
numItems = input("How many items do you want? ")
myTup = ()
myList = []
for x in range(int(numItems)):
itemName = input("Enter item name: ")
itemPrice = input("Enter item price: ")
myTup = (itemPrice, itemName)
myList.append(myTup)
myList.sort()
for x in range(len(myList)): print(myList[x][1] + " = " + myList[x][0])