首页 > 解决方案 > 在 Python 中,如何用正确的最小值和最大值索引星期的名称?

问题描述

我知道这可能是一个愚蠢的问题,但我做了我的研究,我没有找到任何可以解决它的东西。如果有人可以帮助我,我会很高兴的。

我正在尝试用正确的 min() 和 max()索引一周中的哪一天

Monday= input('Enter the temperature for monday:')
Tuesday= input('Enter the temperature for Tuesday:')
Wednesday= input('Enter the temperature for Wednesday:')
Thrusday= input('Enter the temperature for Thrusday:')
Friday= input('Enter the temperature for Friday:')

list=[周一、周二、周三、周四、周五]

for i in list:
    print(f" Tuesday was the coldest day with the temperature: {min(list)}")
    print(f"Tuesday was the warmest day with the temperature: {max(list)}")
    break

不管怎么说,还是要谢谢你!

标签: pythonlistfor-loopindexingweekday

解决方案


这是这个问题的一个变体:Find maximum value and index in a python list? (发布的答案对于新手来说可能有点难以理解,所以我将在下面展开而不是标记为重复)。

您希望尽可能地将数据保存在一起。否则,如果您对列表进行排序 - 这是找出最高温度的最简单方法,而无需跟踪它是一周中的哪一天 - 当您进行排序时,它将失去秩序。

注意:不要将变量称为“列表”。你会遇到各种各样的问题。

注意:对于任何重要的事情,我都会编写一个类并包含自定义比较器函数(等于、小于、大于)。

list_of_days = [['Monday',20], ['Tuesday',22], ['Wednesday',16], ['Thursday',24], ['Friday',22]]

为了跟踪列表中的位置并将新的温度写回列表,enumerate应该使用。

for di,d in enumerate(list_of_days):
    day_prompt = f'Enter the temperature for {d[0]}: '
    day_temp = input(day_prompt)
    list_of_days[di][1] = int(day_temp)

现在有一个更新的列表。请注意,如果输入的不是数字,这将失败。

hottest_day = max(list_of_days, key=lambda item: item[1])
print(f'{hottest_day[0]} was the hottest day of the week with a temperature of {str(hottest_day[1])}')

这其中的关键部分是key参数,以便告诉max函数使用第二个元素来比较列表的内容。


推荐阅读