○ 알고리즘, 자료구조/2021 알고리즘
매달 월 매출 | 파일 불러오기 구분자 활용하기
0ver-grow
2021. 6. 1. 11:29
반응형
시행착오1 : 출력 결과 [] [] [] 으로 출력되면 df 아닌가?
total = 0
with open("data/chicken.txt", "r") as f :
for i in f :
sum_data = (i.strip()).split(":")
print(sum_data)
</> 실행 결과
['1일', ' 453400']
['2일', ' 388600']
['3일', ' 485300']
['4일', ' 477900']
['5일', ' 432100']
['6일', ' 665300']
['7일', ' 592500']
['8일', ' 465200']
놉. 각 라인은 list 타입이다.
시행착오2 : print(sum_data[1]) # 왜 액수만 나오는거지??
total = 0
with open("data/chicken.txt", "r") as f :
for i in f :
sum_data = (i.strip()).split(":")
print(sum_data[1]) # 왜 액수만 나오는거지??
</> 실행 결과
453400
388600
485300
477900
432100
665300
592500
각 라인은 list 타입이므로 액수가 속해있는 열은 인덱스 1이 맞다
시행착오3 : 액수만 있는 sum_data[1]을 출력했더니 한번에 453500이 아닌 왜 한자리씩(4 5 3 4 0 0) 출력되는걸까?
total = 0
num = 0
with open("data/chicken.txt", "r") as f :
for i in f :
sum_data = (i.strip()).split(":")
for sales in sum_data[1] :
print(sales)
내가 푼 정답 : 한자리씩 나누지 않도록 내장함수를 사용하자
total = 0
num = 0
with open("data/chicken.txt", "r") as f :
for i in f :
sum_data = (i.strip()).split(":") # list type
for sales in sum_data[1].split() :
total += int(sales)
num += 1
print(total / num)
모범 답안
with open('data/chicken.txt', 'r') as f:
total_revenue = 0
total_days = 0
for line in f:
data = line.strip().split(": ")
revenue = int(data[1]) # 그날의 매출
total_revenue += revenue
total_days += 1
print(total_revenue / total_days)
반응형