python - 在 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
不管怎么说,还是要谢谢你!
解决方案
这是这个问题的一个变体: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
函数使用第二个元素来比较列表的内容。
推荐阅读
- python-3.x - 课堂上的sklearn方法
- r - 计算元素出现次数和平均值的列
- wcf - .net 核心的 SecurityBindingElement.EnableUnsecuredResponse 等价物?
- powershell - 通过 Powershell 破坏格式字符串进行 SSAS 部署
- delphi - 如何通过右键单击在 TTabControl 中选择选项卡
- powershell - 使用 DOMAIN\USERNAME 时 New-PSSession 失败,但使用 USERNAME@DOMAIN.com 有效?
- java - Android Studio 运行警告:W/:无法打开“/system/framework/WfdCommon.jar”:没有这样的文件或目录
- html - 基于 URL 参数的动态文本
- angular - 如何在 Angular 应用程序中使用 Puppeteer
- javascript - 如何在多个文件中使用 ES6 模块系统?