在 Python 中,如何使用正确的最小值和最大值为星期名称编制索引?
In Python how can I index the name of the week with the correct min and max?
我知道这可能是一个愚蠢的问题,但我进行了研究,但没有找到任何可以解决该问题的方法。如果有人能帮助我,我会很高兴。
我正在尝试使用正确的 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
谢谢!
这是这个问题的一个变体:(那里发布的答案对于新手来说可能有点难以理解,所以我将在下面展开而不是标记为重复)。
您想尽可能地将您的数据放在一起。否则,如果您对列表进行排序——这是找出最高温度的最简单方法,而无需跟踪它是一周中的哪一天——当您进行排序时,它将失去顺序。
注意: 不要将变量称为“list”。你会遇到各种各样的问题。
注意:对于任何重要的事情,我都会写一个 class 并包括自定义比较器函数(等于、小于、大于)。
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
函数使用第二个元素来比较列表的内容。
我知道这可能是一个愚蠢的问题,但我进行了研究,但没有找到任何可以解决该问题的方法。如果有人能帮助我,我会很高兴。
我正在尝试使用正确的 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
谢谢!
这是这个问题的一个变体:
您想尽可能地将您的数据放在一起。否则,如果您对列表进行排序——这是找出最高温度的最简单方法,而无需跟踪它是一周中的哪一天——当您进行排序时,它将失去顺序。
注意: 不要将变量称为“list”。你会遇到各种各样的问题。
注意:对于任何重要的事情,我都会写一个 class 并包括自定义比较器函数(等于、小于、大于)。
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
函数使用第二个元素来比较列表的内容。