每月温度的文本文件到集合

Text File of Monthly Temps into Set

我有一年中几个月的 .txt 文件,其中包含每日温度读数。

我想获取从 .readlines() 创建的列表,每个月分开并消除任何重复值(使用集合)。

这是文本文件:

January:23,23,23,21,21,23,23,22,22,23,23,23,22,22,22,23,23,23,22,19,22,23,22,22,22,22,22,23,23,23,22
February:23,22,26,26,26,27,27,27,26,26,26,27,27,3,26,26,27,26,26,26,27,26,26,26,26,26,26
March:19,18,18,18,23,21,31,33,33,22,19,18,18,18,4,5,31,33,19,18,19,18,18,18,23,21,31,33,33,22
April:40,17,17,17,19,19,18,19,22,22,19,19,18,19,23,17,19,5,18,19,17,19,19,18,19,22,22,19,19,18
May:1,19,19,18,19,22,22,19,19,18,36,35,22,22,22,19,33,27,6,23,22,22,19,22,23,23,22,22,19,19
June:33,23,19,18,19,22,22,19,19,18,36,35,22,22,19,19,18,22,19,19,8,36,22,19,19,18,36,35,22
July:23,23,23,23,23,33,33,33,22,22,19,19,18,36,35,49,19,19,18,36,35,9,19,19,18,36,35,22
August:18,23,36,35,49,19,19,18,36,35,49,19,19,18,36,35,22,19,19,18,36,35,49,15,19,18,36,35,22
September:18,36,35,49,19,19,18,36,35,49,19,19,18,36,35,22,23,23,18,36,35,49,14,19,19,18,36,35,22
October:18,36,35,49,19,19,18,36,35,49,19,19,18,36,35,22,23,23,22,22,33,22,19,19,19,19,18,36,35,22
November:18,36,35,49,19,19,18,36,35,49,19,19,18,36,35,22,23,23,23,24,22,22,19,18,36,35,49,19,21,11
December:18,36,35,49,19,19,40,23,22,22,23,18,36,35,49,19,19,18,36,18,36,35,12,19,19,18,23,22,22,23

这是我目前所拥有的:

year_weather = None
months = ['January', 'Feburary', 'March', 'April', 'May', 'June', 'July',
          'August', 'September', 'October', 'November', 'December']

def open_weather():
    global year_weather
    weather = open('yearly_temperature.txt')
    year_weather = weather.readlines() 
    return year_weather

def month_temp(year_weather, months):
    output = []
    for x in months:
        for y in year_weather:
            output.append(months[x])
            output.append(year_weather[y])
    return output

我知道我必须创建一个 For 循环,它以月份为单位获取每个值,并将 year_weather 中的每个相应值添加到它,即月份中的一月 + year_weather 中该月的值.

但我似乎想不通。

有什么帮助吗?谢谢

这就是你能做的。我们取每一行,去掉月份和换行符,然后用逗号分隔。然后我们将列表转换成一个集合,瞧。此外,无需将 year_weather 声明为全局变量。

months = ['January', 'Feburary', 'March', 'April', 'May', 'June', 'July',
          'August', 'September', 'October', 'November', 'December']

def open_weather():
    weather = open('yearly_temperatures.txt')
    year_weather = weather.readlines() 
    return year_weather

def month_temp(year_weather, months):
    output = []
    for i in range(len(months)):
        output.append((months[i], set(year_weather[i].lstrip(months[i] + ":").strip("\n").split(","))))
    return output

yw = open_weather()
print(month_temp(yw, months))