python - 我无法获得元组的最小值或最大值
问题描述
total_price = []
for i in range (5):
try:
price = list (input ("Enter the price of the sweet: "))
except ValueError:
print("Enter an integer")
total_price.append(price)
print (total_price)
print ("The most expensive sweet is " + str (max(total_price)))
print ("The least expensive sweet is" + str (min(total_price)))
这就是它的输出
Enter the price of the sweet: 10
Enter the price of the sweet: 20
Enter the price of the sweet: 30
Enter the price of the sweet: 40
Enter the price of the sweet: 50
[['1', '0'], ['2', '0'], ['3', '0'], ['4', '0'], ['5', '0']]
The most expensive sweet is ['5', '0']
The least expensive sweet is['1', '0']
>>>
我已经设法到达那个阶段,但我仍然遇到问题,因为某种原因它正在分离数组中的值。
解决方案
如果您将价格存储在一个可迭代的列表中,您就可以找到最昂贵糖果的价格。如:
prices = []
for i in range(5):
try:
sweet_price = int(input("Enter price: "))
except ValueError:
print("ErrorMessage")
prices.append(sweet_price)
highest_price = max(prices)
见https://docs.python.org/3/library/functions.html#max
如标题所示,要在元组中查找最大值,请尝试
max(list(prices))