파이썬 리스트 합계
python
파이썬 텍스트 파일 리스트로 받아서 요소 합계를 구하려는데 오류가 나는데 어떻게 해야하나요?
infile = open("/Users/Jinwoo Baek/Desktop/DSU/교과/프로그래밍입문/test/test2.txt", "r", encoding='utf-8') s = infile.readlines()
t = sum(s)
print("합계 = ", t)
infile.close()
[오류]
t = sum(s)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
-
2017년 12월 10일에 작성됨
댓글달기
조회수 350
1 답변
infile = open("/Users/Jinwoo Baek/Desktop/DSU/교과/프로그래밍입문/test/test2.txt", "r", encoding='utf-8')
s = infile.readlines()
t = 0
for i in s:
t += float(i)
print("합계 = ", t)
infile.close()
readlines()를 호출하면 문자열 리스트가 반환되므로, 숫자 덧셈연산을 원하시면 숫자 자료형으로 형변환을 해줘야합니다.
-
2017년 12월 11일에 작성됨
-
t += float(s[i]) TypeError: list indices must be integers or slices, not str 라는 오류가 나는데 왜이럴까요 ㅠ Jinwoo Baek 2017.12.11 12:00
-
수정했습니다~ 전대호 2017.12.11 12:19
-
감사합니다!! Jinwoo Baek 2017.12.11 12:36