每月临时文本文件集

时间:2016-03-13 09:06:48

标签: list python-3.x file-io 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中该月份的值。

但我似乎无法弄明白。

有任何帮助吗?感谢

1 个答案:

答案 0 :(得分:0)

这是你可以做的。我们采用每一行,删除月份和换行符,然后用逗号分隔。然后我们将列表转换为集合和瞧。此外,无需将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))