티스토리 뷰
iterable이란 자신의 멤버를 한 번에 리턴할 수 있는 객체로 list, str, tuple, dictionary와 같은 것이다.
📌 원본을 유지한 채, 정렬된 리스트 구하기 - sorted
sort() 함수는 원본의 순서를 변경하기 때문에 deep copy 후 sort를 사용하여 정렬해야 되지만
sorted() 함수는 원본은 그대로 두고 정렬하기 때문에 deep copy가 필요 없다.
📌 2차원 리스트 뒤집기 - zip
2차원 리스트를 인자로 받아 행과 열을 뒤집은 값을 반환하는 함수 작성
input : [[1,2,3], [4,5,6], [7,8,9]]
output : [[1,4,7], [2,5,8], [3,6,9]]
zip과 unpacking을 이용하여 변환 가능
def solution(mylist):
return list(map(list, zip(*mylist)))
BUILT-IN FUNCTIONS : ZIP
python의 zip 함수는 각 iterables의 요소를 모으는 iterator를 만든다.
Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator.
# 사용 예 1
mylist = [1, 2, 3]
new_list = [40, 50, 60]
for i in zip(mylist, new_list):
print (i)
# 출력 결과 : (1, 40)\n(2, 50)\n(3, 60)\n
# 사용 예 2 - 여러 개의 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)
#출력 결과 : 493\n124\n66\n305\n
# 사용 예 3 - Key 리스트와 Value 리스트로 딕셔너리 생성하기
animals = ['cat', 'dog', 'lion']
sounds = ['meow', 'woof', 'roar']
animal_sound = dict(zip(animals, sounds))
print(animal_sound)
# 출력 결과 : {'cat': 'meow', 'dog': 'woof', 'lion': 'roar'}
📌 i번째 원소와 i+1번째 원소 - zip
숫자를 담은 리스트를 인자로 받아 i번째 요소와 i+1번째 요소의 차를 담을 리스트를 반환하는 코드를 작성하되, 마지막 원소는 제외한다.
내가 쓴 코드
def solution(mylist):
answer = []
for i in range(len(mylist)-1):
answer.append(abs(mylist[i]-mylist[i+1]))
return answer
zip 함수 이용
def solution(mylist):
answer = []
for number1, number2 in zip(mylist, mylist[1:]):
answer.append(abs(number1 - number2))
return answer
📌 모든 멤버의 type 변환하기 - map
문자열 리스트를 입력 받아, 정수형 리스트로 바꾸어 반환
input : ['1', '100', '33']
output : [1, 100, 33]
내가 쓴 코드
def solution(mylist):
answer = []
for i in range(len(mylist)):
answer.append(int(mylist[i]))
return answer
map(function, iterable)을 사용하면 for문을 사용하지 않고 멤버의 타입을 한 번에 바꿀 수 있다.
def solution(mylist):
return list(map(int, list1))
map 함수는 iterable의 각 원소에 함수를 적용하여 반환한다.
📌 map 함수 응용하기
정수를 담은 2차원 리스트를 인자로 받아 각 원소의 길이를 담은 리스트를 반환하는 함수 작성
def solution(mylist):
answer = list(map(len, mylist))
return answer
프로그래머스 - 파이썬을 파이썬답게 강의를 듣고 정리한 내용
programmers.co.kr/learn/courses/4008
'python' 카테고리의 다른 글
| List comprehension의 if 문 (0) | 2021.04.03 |
|---|---|
| itertools / collections module (0) | 2021.03.08 |
| sequence types 다루기 - join, sequence type의 * 연산 (0) | 2021.03.06 |
| 문자열 다루기 - ljust/center/rjust, string module (0) | 2021.03.06 |
| 정수 다루기 - divmod, int 함수 (0) | 2021.03.06 |
- Total
- Today
- Yesterday
- divmod
- for-else
- ValidataionUtils
- 선형 탐색
- string module
- initBinder
- Django
- valid annotation
- djnago
- 이진 탐색
- 선형 배열
- sequence type
- 출력 형식 지정
- ljust
- python
- tailwind
- Stack
- 직접 주입
- rjust
- postfix notation
- 스택
- 스프링부트
- 의존 주입
- python flag
- most_common
- 파이썬
- 자료구조
- airbnb clone
- springboot
- 양방향 연결 리스트
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | |||
| 5 | 6 | 7 | 8 | 9 | 10 | 11 |
| 12 | 13 | 14 | 15 | 16 | 17 | 18 |
| 19 | 20 | 21 | 22 | 23 | 24 | 25 |
| 26 | 27 | 28 | 29 | 30 |
