Python 실습 - weather data

파이썬 기초

목록 보기
6/15

내 코드와 리더님의 코드를 비교해보자!

내 코드


#실습 6 힘수 종합 프로그램

weather_data = [
    ["2024-11-20", "서울", 15.2, 0.0],
    ["2024-11-20", "부산", 18.4, 0.0],
    ["2024-11-21", "서울", 10.5, 2.3],
    ["2023-11-21", "부산", 14.6, 1.2],
    ["2024-11-22", "서울", 8.3, 0.0],
    ["2024-11-22", "부산", 12.0, 0.0]
] # initial data set, 전역변수


# 도시별 평균 기온 계산하는 함수
def avg_temp(inn): 
    result = []
    def check(inn):
        for i in range(len(weather_data)): #data 개수만큼 횟수 반복
            if weather_data[i][1] == inn:
                result.append(weather_data[i][2])
            else:
                continue
        return result
    
    
    li_result = check(inn)
    #print(li_result)
    #print(len(li_result))
    return sum(li_result) / len(li_result)

#print(avg_temp("서울"))

#도시별 최저 기온 확인하는 함수
def min_temp(inn):
    result = []
    def check(inn):
        for i in range(len(weather_data)):
            if weather_data[i][1] == inn: #기온 거르기
                result.append(weather_data[i][2])
            else:
                continue
        return result #도시 이름 걸러내기
    
    
    li_result = check(inn)
    #print(li_result)
    #print(len(li_result))
    return min(li_result)

#print(min_temp("서울"))

def max_temp(inn):
    result = []
    def check(inn):
        for i in range(len(weather_data)):
            if weather_data[i][1] == inn: #기온 거르기
                result.append(weather_data[i][2])
            else:
                continue
        return result #도시 이름 걸러내기
    
    
    li_result = check(inn)
    #print(li_result)
    #print(len(li_result))
    return max(li_result)

# print(max_temp("서울"))

def precip(inn):
    result = []
    def check(inn):
        for i in range(len(weather_data)):
            if weather_data[i][1] == inn: #강수량 거르기
                result.append(weather_data[i][3])
            else:
                continue
        return result #도시 이름 걸러내기
    li_result = check(inn)

    total = sum(li_result)
    count = 0

    for i in range(len(li_result)):
        if li_result[i] != 0:
            count += 1
        else:
            continue

    return total, count

# total, count = precip("서울")
# print(f"총 {total} mm, 총 {count} 일")

def add_data(date, city, temp, prec):
    emp = [date, city, float(temp), float(prec)]
    weather_data.append(emp)




def data_show():
    print("현재 저장된 날씨 데이터: \n")
    for i in range(len(weather_data)):
        print(f"날짜: {weather_data[i][0]}, 도시: {weather_data[i][1]}, 평균 기온: {weather_data[i][2]} celsius, 강수량: {weather_data[i][3]}mm")   

#data_show()
while True:
    print("[날씨 데이터 분석 프로그램] \n1.평균 기온 계산\n2.최고/최저 기온 찾기\n3.강수량 분석\n4.날씨 데이터 추가\n5.전체 데이터 출력\n6.종료(오소정)\n")
    inn = input("원하는 기능의 번호를 입력하세요: ")
    if inn == "1":
        inn2 = input("도시의 이름을 선택하세요(서울 부산 중 택 1): ")
        if inn2 == "서울" or inn2 == "부산":
            print(f"{inn2}의 평균 기온: {avg_temp(inn2):.2f} celsius \n\n\n")
        
        else:
            print("잘못된 입력입니다.")
    elif inn == "2":
        inn2 = input("도시의 이름을 선택하세요(서울 부산 중 택 1): ")
        if inn2 == "서울" or inn2 == "부산":
            print(f"{inn2}의 최고 기온: {max_temp(inn2)} celsius, 최저 기온: {min_temp(inn2)} celsius\n\n\n")
        
        else:
            print("잘못된 입력입니다.")
    elif inn == "3":
        inn2 = input("도시의 이름을 선택하세요(서울 부산 중 택 1): ")
        if inn2 == "서울" or inn2 == "부산":
            total, count = precip(inn2)
            print(f"{inn2}의 총 강수량: {total} mm\n{inn2}에 강수량이 있었던 날: {count}일\n\n\n")
        else:
            print("잘못된 입력입니다.")       
    elif inn == "4":
        date = input("\n날짜를 입력하세요. (YYYY-MM-DD): ")
        city = input("\n도시를 입력하세요.: ")
        temp = input("\n평균 기온을 입력하세요. (celsius): ")
        prec = input("\n강수량을 입력하세요.(mm): ")
        add_data(date, city, temp, prec)
        print(f"{city}의 날씨 데이터가 추가되었습니다. \n\n\n")
    elif inn == "5":
        data_show()
    elif inn == "6":
        break
    else:
        print("잘못돤 입력입니다.\n")

사실상 도시 이름을 입력 받아 데이터 중 걸러내는 작업이 각 함수마다 반복되고 있다.
->코드의 간략화를 위해 도시의 이름을 입력 받아 데이터를 거르는 함수를 만드는 것도 좋을 것이다!

리더님 코드 예시

#실습6. 함수 종합 프로그래밍
#초기 날씨데이터
weather_data = [
    ["2024-11-20", "서울", 15.2, 0.0],
    ["2024-11-20", "부산", 18.4, 0.0],
    ["2024-11-21", "서울", 10.5, 2.3],
    ["2024-11-21", "부산", 14.6, 1.2],
    ["2024-11-22", "서울", 8.3, 0.0],
    ["2024-11-22", "부산", 12.0, 0.0]
]
# 평균기온함수
def avg_temperatures(weather_data):
    city = input("도시 이름을 입력하세요: ")
    total = 0
    count = 0
    for data in weather_data:
        if data[1] == city:
            total += data[2]
            count += 1
    return city, total / count

    # temp = filter(lambda x: x[1] == city,  weather_data) # 도시 추출
    # temperatures = list(map(lambda x : x[2], temp)) # 기온 추출
    # if not temperatures:
    #     return city, None
    # else:
    #     return city, sum(temperatures) / len(temperatures)

#최고/최저 기온함수
def maxmin_temperatures(weather_data):
    city = input("도시 이름을 입력하세요: ")
    temperatures = [data[2] for data in weather_data if data[1] == city]
    # temp = filter(lambda x: x[1] == city,  weather_data) # 도시 추출
    # temperatures = list(map(lambda x : x[2], temp)) # 기온 추출
    if not temperatures: #해당 되는 도시의 데이터가 0개인 경우
        return city, None, None #값이 없음 리턴
    else:
        return city, max(temperatures), min(temperatures)

# 강수량과 비가온날 찾는 함수    
def total_rain_day(weather_data):
    city = input("도시 이름을 입력하세요: ")
    temp = filter(lambda x: x[1] == city,  weather_data) # 도시 추출
    rain =  list(map(lambda x : x[3], temp)) # 강수량 추출
    total_rain = sum(rain) # 총 강수량
    rain_day = len(list(filter(lambda x : x > 0 , rain))) # 비가온날
    return city, total_rain, rain_day

# 데이터 추가 함수
def add_weather(weather_data):
    date = input("날짜를 입력하세요 (YYYY-MM-DD): ")
    city = input("도시 이름을 입력하세요: ")
    temperatures = float(input("평균 기온을 입력하세요 (℃ ): "))
    rain = float(input("강수량을 입력하세요 (mm): "))
    weather_data.append([date, city, temperatures, rain])
    return city

# 전체 데이터 출력 함수
def all_data(weather_data):
    print("\n현재 저장된 날씨 데이터:")
    for data in weather_data:
        print(f"날짜: {data[0]}, 도시: {data[1]}, 평균기온: {data[2]}℃ , 강수량: {data[3]}mm")

def main_program():
    while True:
        print("\n[날씨 데이터 분석 프로그램]")
        print("1. 평균 기온 계산")
        print("2. 최고/최저 기온 찾기")
        print("3. 강수량 분석")
        print("4. 날씨 데이터 추가")
        print("5. 전체 데이터 출력")
        print("6. 종료")
        choice = input("원하는 기능의 번호를 입력하세요: ")
        if choice == "1":
            city, avg_result = avg_temperatures(weather_data) # 도시의 평균 기온 계산 함수
            if avg_result is None:
                print(f"{city}의 정보가 존재하지 않습니다.")
            else:
                print(f"{city}의 평균 기온: {avg_result:.2f}℃")
           # print(list(filter(lambda x: x[1] == city,  weather_data)))
        elif choice == "2":
            city, max_value, min_value =  maxmin_temperatures(weather_data) #도시의 최고/최저 기온찾는 함수
            if max_value is None:
                print(f"{city}의 정보가 존재하지 않습니다.")
            else:
                print(f"{city}의 최고기온: {max_value}℃ , 최저기온: {min_value}℃")
        elif choice == "3":
            city, total_rain, rain_day =  total_rain_day(weather_data) # 강수량과 비온날 찾는 함수
            print(f"{city}의 총 강수량: {total_rain:.1f}mm")
            print(f"{city}의 비가온날: {rain_day}일")
        elif choice == "4":
            city = add_weather(weather_data) # 데이터 추가 함수
            print(f"{city}의 날씨 데이터가 추가되었습니다.")
        elif choice == "5":
            all_data(weather_data) # 전체 데이터 출력 함수
        elif choice == "6":
            print("프로그램을 종료합니다.")
            break
        else:
            print("1~6까지의 번호를 입력하세요")


# 프로그램 실행 함수
main_program()

Tip.
특수문자는 한글 'ㄹ' + 한자 키 누른 후 선택

0개의 댓글