You are on page 1of 10

입력 처리

입력처리: input()
• 입력 처리
• 1줄에 1개 정수
• 1줄에 여러 개 정수
• 여러 줄
• Python 입력처리 함수
• input()
• readline()
• readlines()

2
입력 -> 파이썬 코드 실행 -> 출력 비교
• cat input.txt | python helloworld.py
• 윈도우: type input.txt
• 결과 임시 출력: cat input.txt | python helloworld.py > temp.txt
• 결과비교
• 정답파일
• output.txt
• Windows
• fc.exe temp.txt output.txt (/l option: ASCII)
• Linux
• diff temp.txt output.txt (-b option: ignore-space-change)

3
map() 함수 이용하기
• map(int, input().split())

4
여러 개 정수 입력도 map() 함수 이용
• map(int, input().split()) + list

5
파이썬 map() 함수
• map(function, iterable)
• 두번째 반복가능한 자료형에 대해서 function 적용
• 예: 정수 리스트를 더하기
• 예: 문자열 리스트를 정수로 변환하기
• 예)
• map( inc(n), input_list)
• map(int, input_str)

• 참고
• 1회성 함수: Lambda 함수
• map(lambda x: x+1, input_list)
Python map(), filter(), reduce()
• map(function, iterable)
• filter(function, iterable)
• function이 True를 반환하는 element의 iterator
• filter(lambda x: x % 2 == 0, [1,2,3,4,5] )
• reduce(function, iterable)
• element에 function을 왼쪽부터 하나씩 누적해서 2개 인자에 대해서 적용
• reduce(lambda x, y: x + y, [1,2,3,4,5])
파이썬 input() 과 readline() 차이
• input()
• prompt 메시지에서 개행문자 삭제후 문자열 반환
• 키보드 입력을 버퍼에 보관
• sys.stdin.readline()
• input()과 같은 동작
• Prompt 메시지 파라미터로 받지 않고, 개행문자 포함하여 반환 (.rstrip
으로 제거)
• 속도가 빠름: 줄 단위 읽기
• 참고
• Java: Scanner vs. BufferedReader
• C++: cout vs. printf
입력 카운트 + 여러 줄 입력 readlines()
• input() + sys.stdin.readlines() loop

9
입력 카운트 + 여러 줄의 정수 리스트
• input() + readlines() list + loop

10

You might also like