-
파이썬을 파이썬답게 (2)개발노트 2019. 9. 7. 14:35
1. 2차원 리스트 뒤집기
-다음을 만족하는 함수, solution을 완성해주세요.
- solution 함수는 이차원 리스트, mylist를 인자로 받습니다
- solution 함수는 mylist 원소의 행과 열을 뒤집은 한 값을 리턴해야 합니다.
예를 들어 mylist [ [1,2,3], [4,5,6], [7,8,9] ]가 주어진 경우,
solution 함수는 [[1, 4, 7], [2, 5, 8], [3, 6, 9]] 을 리턴하면 됩니다.
Zip 함수를 사용합니다.
>>> mylist = [ [1,2,3], [4,5,6], [7,8,9] ] >>> new_list = list(map(list, zip(*mylist))) >>> new_list [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
zip 함수에 대해
파이썬 3 한글 번역 - zip에 따르면
zip(*iterables)는 각 iterables의 요소들을 모으는 이터레이터를 만듭니다.
튜플의 이터레이터를 돌려주는데, i 번째 튜플은 각 인자로 전달된 시퀀스나 이 트러블의 i 번째 요소를 포함합니다.mylist = [ 1,2,3 ] new_list = [ 40, 50, 60 ] for i in zip(mylist, new_list): print (i) (1, 40) (2, 50) (3, 60)
사용 예 #1 - 여러 개의 Iterable 동시에 순회할 때 사용
list1 = [1, 2, 3, 4] list2 = [100, 120, 30, 300] list3 = [392, 2, 33, 1] answer = [] for i, j, k in zip(list1, list2, list3): print( i + j + k )
사용 예 #2 - Key 리스트와 Value 리스트로 딕셔너리 생성하기
파이썬의 zip 함수와 dict 생성자를 이용하면 코드 단 한 줄로, 두 리스트를 합쳐 딕셔너리로 만들 수 있습니다.
animals = ['cat', 'dog', 'lion'] sounds = ['meow', 'woof', 'roar'] answer = dict(zip(animals, sounds)) # {'cat': 'meow', 'dog': 'woof', 'lion': 'roar'}
2. 모든 멤버의 type 변환하기
-문자열 리스트 mylist를 입력받아, 이 리스트를 정수형 리스트로 바꾼 값을 리턴하는 함수, solution을 만들어주세요.
예를 들어 mylist가 ['1', '100', '33']인 경우, solution 함수는 [1, 100, 33]을 리턴하면 됩니다.
Map함수를 사용합니다.
>>> list1 = ['1', '100', '33'] >>> list2 = list(map(int, list1)) >>> list2 [1, 100, 33]
-정수를 담은 이차원 리스트, mylist 가 solution 함수의 파라미터로 주어집니다. solution 함수가 mylist 각 원소의 길이를 담은 리스트를 리턴하도록 빈칸을 완성해보세요.
Map 함수를 사용합니다.
원소의 길이를 구하기 때문에 Len함수도 사용합니다.
>>> mylist = [[1],[2]] >>> mylist2 = list(map(len, mylist)) >>> mylist2 [1, 1] >>> mylist = [[1,2],[3,4],[5]] >>> mylist2 = list(map(len, mylist)) >>> mylist2 [2, 2, 1]
3. sequence 멤버를 하나로 이어 붙이기
-문자열 리스트 mylist를 입력받아, 이 리스트의 원소를 모두 이어 붙인 문자열을 리턴하는 함수, solution을 만들어주세요. 예를 들어 mylist가 ['1', '100', '33']인 경우, solution 함수는 '110033'을 리턴하면 됩니다.
Join 함수를 사용합니다.
>>> my_list = ['1', '100', '33'] >>> answer = ''.join(my_list) >>> answer '110033'
4. 삼각형 별 찍기
-이 문제에는 표준 입력으로 정수 n이 주어집니다.
별(*) 문자를 이용해 높이가 n인 삼각형을 출력해보세요.*연산자를 사용합니다.
for i in range(0, n+1): print('*'*i)
5. 곱집합(Cartesian product) 구하기 - product
itertools.product를 이용하면, for 문을 사용하지 않고도 곱집합을 구할 수 있습니다.
>>> import itertools >>> iterable1 = 'ABCD' >>> iterable2 = 'xy' >>> iterable3 = '1234' >>> print(list(itertools.product(iterable1, iterable2, iterable3))) [('A', 'x', '1'), ('A', 'x', '2'), ('A', 'x', '3'), ('A', 'x', '4'), ('A', 'y', '1'), ('A', 'y', '2'), ('A', 'y', '3'), ('A', 'y', '4'), ('B', 'x', '1'), ('B', 'x', '2'), ('B', 'x', '3'), ('B', 'x', '4'), ('B', 'y', '1'), ('B', 'y', '2'), ('B', 'y', '3'), ('B', 'y', '4'), ('C', 'x', '1'), ('C', 'x', '2'), ('C', 'x', '3'), ('C', 'x', '4'), ('C', 'y', '1'), ('C', 'y', '2'), ('C', 'y', '3'), ('C', 'y', '4'), ('D', 'x', '1'), ('D', 'x', '2'), ('D', 'x', '3'), ('D', 'x', '4'), ('D', 'y', '1'), ('D', 'y', '2'), ('D', 'y', '3'), ('D', 'y', '4')]
product 이외에도 다양한 반복자가 존재합니다.