05. 데이터 구조

데이터 구조(Data Structure)란 데이터에 편리하게 접근하고, 변경하기 위해서 데이터를 저장하거나 조작하는 방법을 말한다.

Program = Data Structure + Algorithm

             Niklaus Wirth

데이터 구조 (Data Structure)

  • 순서가 있는 (ordered) 데이터 구조

    • 문자열 (String)

    • 리스트 (List)

  • 순서가 없는 (unordered) 데이터 구조

    • 세트 (Set)

    • 딕셔너리 (Dictionary)

  • 데이터 구조에 적용 가능한 Built-in Function

5.1 문자열 (String)

  • 문자들의 나열 (sequence of characters)

  • 문자열의 특징

    • 변경할 수 없고(immutable)

    • 순서가 있고(ordered)

    • 순회 가능한(iterable)

  • 문자열의 다양한 조작법(method) : 파이썬 문서

5.1.1 조회/탐색

.find(x)

x의 첫 번째 위치를 반환합니다. 없으면, -1을 반환합니다.

# 변수명이 a인 문자열을 만들어봅시다.

a = 'apple'
# find 메서드로 문자열에 p가 있는지 찾아봅시다.

a.find('p')
1
# find 메서드로 문자열에 z가 있는지 찾아봅시다.

a.find('z')
-1

.index(x)

x의 첫번째 위치를 반환합니다. 없으면, 오류가 발생합니다.

# 변수명이 a인 문자열을 만들어봅시다.

a = 'apple'
# index 메서드로 문자열의 p의 위치를 확인해봅시다.

a.index('p')
1
# index 메서드로 문자열의 z의 위치를 확인해봅시다.

a.index('z')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_1184/3187919519.py in <module>
      1 # index 메서드로 문자열의 z의 위치를 확인해봅시다.
      2 # =====
----> 3 a.index('z')

ValueError: substring not found

5.1.2 문자열 변경

.replace(old, new[, count])

바꿀 대상 글자를 새로운 글자로 바꿔서 반환합니다.

count를 지정하면 해당 갯수만큼만 시행합니다.

# 변수명이 a, b인 문자열을 만들어봅시다.

a = 'yaya!'
b = 'wooooowoo'
# replace 메서드로 변수 a의 글자 y를 h로 변경해봅시다.

a.replace('y', 'h'), a       # 원본이 바뀌지 않음
('haha!', 'yaya!')
# replace 메서드로 변수 b의 글자 o 2개를 _로 변경해봅시다.

b.replace('o', '_', 2)
'w__ooowoo'

.strip([chars])

특정한 문자들을 지정하면, 양쪽을 제거하거나 왼쪽을 제거하거나(lstrip), 오른쪽을 제거합니다(rstrip).

지정하지 않으면 공백을 제거합니다.

# 변수명이 a, b인 문자열을 만들어봅시다.

a = '   hello!  \n'
b = 'hihihihahahahihi'
# stript 메서드로 변수 a의 양쪽 공백을 제거해 봅시다.

a.strip()
'hello!'
# lstript 메서드로 변수 a의 왼쪽 공백을 제거해 봅시다.

a.lstrip()
'hello!  \n'
# rstrip 메서드로 변수 b의 오른쪽에서 글자 hi를 제거해 봅시다.

b.rstrip('hi')
'hihihihahaha'

.split([chars])

문자열을 특정한 단위로 나누어 리스트로 반환합니다.

# 변수명이 a인 문자열을 만들어봅시다.

a = 'a_b_c'
# split 메서드로 문자열의 _를 기준으로 나누어 리스트로 반환해봅시다.

'a_b_c'.split('_')
['a', 'b', 'c']
# 사용자의 입력값을 받아 변수 i에 저장합니다.
# 입력받은 문자열을 split 메서드로 공백을 기준으로 나누어 리스트로 반환해봅시다.

i = input()
i.split()
 안녕 나는 지수야 헬륨가스 먹었더니 요롷게 됐징
['안녕', '나는', '지수야', '헬륨가스', '먹었더니', '요롷게', '됐징']

'separator'.join(iterable)

특정한 문자열로 만들어 반환합니다.

반복가능한(iterable) 컨테이너의 요소들을 separator(구분자)로 합쳐(join()) 문자열로 반환합니다.

# 변수명이 word인 문자열, words인 리스트를 만들어 봅시다.

word = '배고파'
words = ['안녕', 'hello']
# join 메서드로 변수 word의 문자열 사이에 !를 넣은 결과를 반환해봅시다.

'!'.join(word)
'배!고!파'
# join 메서드로 변수 words의 문자들을 하나로 합친 결과를 반환해봅시다.

' '.join(words)
'안녕 hello'

.capitalize(), .title(), .upper()

  • .capitalize() : 앞글자를 대문자로 만들어 반환합니다.

  • .title() : 어포스트로피나 공백 이후를 대문자로 만들어 반환합니다.

  • .upper() : 모두 대문자로 만들어 반환합니다.

# 변수명이 a인 문자열을 만들어봅시다.

a = 'hI! Everyone, I\'m kim'
# capitalize 메서드로 문자열의 앞글자를 대문자로 만들어 반환해봅시다.

a.capitalize()
"Hi! everyone, i'm kim"
# title 메서드로 문자열의 각각의 단어 앞글자를 대문자로 만들어 반환해봅시다.

a.title()
"Hi! Everyone, I'M Kim"
# upper 메서드로 문자열을 모두 대문자로 만들어 반환해봅시다.

a.upper()
"HI! EVERYONE, I'M KIM"
# print 함수로 변수 a를 출력하여 원본데이터를 확인해봅시다.

print(a)
hI! Everyone, I'm kim

.lower(), .swapcase()

  • lower() : 모두 소문자로 만들어 반환합니다.

  • swapcase() : 대 <-> 소문자로 변경하여 반환합니다.

# 변수명이 a인 문자열을 만들어봅시다.

a = 'hI! Everyone, I\'m kim'
# lower 메서드로 문자열을 모두 소문자로 만들어 반환해봅시다.

a.lower()
"hi! everyone, i'm kim"
# swapcase 메서드로 문자열의 대소문자를 서로 변경하여 반환해봅시다.

a.swapcase()
"Hi! eVERYONE, i'M KIM"
# print 함수로 변수 a를 출력하여 원본데이터를 확인해봅시다.

print(a)
hI! Everyone, I'm kim

기타 문자열 관련 검증 메소드 : 참/거짓 반환

.isalpha(), .isdecimal(), .isdigit(), .isnumeric(), .isspace(), .isupper(), .istitle(), .islower()
+-------------+-----------+-------------+----------------------------------+
| isdecimal() | isdigit() | isnumeric() |          Example                 |
+-------------+-----------+-------------+----------------------------------+
|    True     |    True   |    True     | "038", "੦੩੮", "038"             |
|  False      |    True   |    True     | "⁰³⁸", "🄀⒊⒏", "⓪③⑧"          |
|  False      |  False    |    True     | "↉⅛⅘", "ⅠⅢⅧ", "⑩⑬㊿", "壹貳參"   |
|  False      |  False    |  False      | "abc", "38.0", "-38"             |
+-------------+-----------+-------------+----------------------------------+
# dir 함수로 문자열이 가지고 있는 메소드를 확인할 수 있습니다.

dir('string')
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rmod__',
 '__rmul__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'capitalize',
 'casefold',
 'center',
 'count',
 'encode',
 'endswith',
 'expandtabs',
 'find',
 'format',
 'format_map',
 'index',
 'isalnum',
 'isalpha',
 'isascii',
 'isdecimal',
 'isdigit',
 'isidentifier',
 'islower',
 'isnumeric',
 'isprintable',
 'isspace',
 'istitle',
 'isupper',
 'join',
 'ljust',
 'lower',
 'lstrip',
 'maketrans',
 'partition',
 'removeprefix',
 'removesuffix',
 'replace',
 'rfind',
 'rindex',
 'rjust',
 'rpartition',
 'rsplit',
 'rstrip',
 'split',
 'splitlines',
 'startswith',
 'strip',
 'swapcase',
 'title',
 'translate',
 'upper',
 'zfill']

5.2 리스트 (List)

  • 순서가 있는 시퀀스, 인덱스로 접근

  • 문자열의 특징

    • 변경 가능하고(mutable)

    • 순서가 있고(ordered)

    • 순회 가능한(iterable)

5.2.1 값 추가 및 삭제

.append(x)

리스트에 값을 추가할 수 있습니다.

# 변수명이 cafe인 리스트를 만들어봅시다.

cafe = ['starbucks', 'tomntoms', 'hollys']
print(cafe)
['starbucks', 'tomntoms', 'hollys']
# append 메서드로 리스트에 banapresso를 추가해봅시다.

cafe.append('banapresso')
print(cafe)
['starbucks', 'tomntoms', 'hollys', 'banapresso']

.extend(iterable)

리스트에 iterable(list, range, tuple, string [주의]) 값을 붙일 수가 있습니다.

# extend 메서드로 변수 cafe에 ['wcafe', '빽다방']를 추가해봅시다.

cafe.extend(['wcafe', '빽다방'])
print(cafe)
['starbucks', 'tomntoms', 'hollys', 'banapresso', 'wcafe', '빽다방']
# += 연산자로 변수 cafe에 ['mc_cafe', 'droptop']를 추가해봅시다.
# 앞서 배운 list concatenate와 동일합니다.

cafe += ['mc_cafe', 'droptop']
print(cafe)
['starbucks', 'tomntoms', 'hollys', 'banapresso', 'wcafe', '빽다방', 'mc_cafe', 'droptop']
# append vs extend
# append 메서드로 변수 cafe에 ['coffeenie']를 추가해봅시다.

cafe.append(['coffeenie'])
print(cafe)
['starbucks', 'tomntoms', 'hollys', 'banapresso', 'wcafe', '빽다방', 'mc_cafe', 'droptop', ['coffeenie']]
# append vs extend
# extend 메서드로 변수 cafe에 ['twosome_place']를 추가해봅시다.

cafe.extend(['twosome_place'])
print(cafe)
['starbucks', 'tomntoms', 'hollys', 'banapresso', 'wcafe', '빽다방', 'mc_cafe', 'droptop', ['coffeenie'], 'twosome_place']
# extend 메서드로 변수 cafe에 문자열 ediya를 추가해봅시다.

cafe.extend('ediya')
print(cafe)
['starbucks', 'tomntoms', 'hollys', 'banapresso', 'wcafe', '빽다방', 'mc_cafe', 'droptop', ['coffeenie'], 'twosome_place', 'e', 'd', 'i', 'y', 'a']

.insert(i, x)

정해진 위치 i에 값을 추가합니다.

# insert 메서드로 변수 cafe 첫번째에 문자열 start를 넣어봅시다.

cafe.insert(0, 'start')
print(cafe)
['start', 'starbucks', 'tomntoms', 'hollys', 'banapresso', 'wcafe', '빽다방', 'mc_cafe', 'droptop', ['coffeenie'], 'twosome_place', 'e', 'd', 'i', 'y', 'a']
# insert 메서드로 변수 cafe 마지막에 문자열 end를 넣어봅시다.
# 마지막 위치는 len함수를 이용합니다.

cafe.insert(len(cafe), 'end')
print(cafe)
['start', 'starbucks', 'tomntoms', 'hollys', 'banapresso', 'wcafe', '빽다방', 'mc_cafe', 'droptop', ['coffeenie'], 'twosome_place', 'e', 'd', 'i', 'y', 'a', 'end']
# insert 메서드로 변수 cafe 길이보다 큰 인덱스에 문자열 !를 넣어봅시다.
# 리스트의 길이를 넘어서는 인덱스는 마지막에 아이템이 추가됩니다.

cafe.insert(len(cafe)+100, '!')
print(cafe)
['start', 'starbucks', 'tomntoms', 'hollys', 'banapresso', 'wcafe', '빽다방', 'mc_cafe', 'droptop', ['coffeenie'], 'twosome_place', 'e', 'd', 'i', 'y', 'a', 'end', '!']

.remove(x)

리스트에서 값이 x인 것을 삭제합니다.

# 변수명이 numbers인 리스트를 만들어봅시다.
numbers = [1, 2, 3, 1, 2]
# remove 메서드로 1을 삭제 해봅시다.

numbers.remove(1)
print(numbers)
[2, 3, 1, 2]
# remove 메서드로 1을 한번 더 삭제 해봅시다.

numbers.remove(1)
print(numbers)
[2, 3, 2]
# remove 메서드로 1을 한번 더 삭제 해봅시다.
# remove는 값이 없으면 오류가 발생합니다. 확인해봅시다.

numbers.remove(1)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_1184/558458917.py in <module>
      2 # remove는 값이 없으면 오류가 발생합니다. 확인해봅시다.
      3 # =====
----> 4 numbers.remove(1)

ValueError: list.remove(x): x not in list

.pop(i)

정해진 위치 i에 있는 값을 삭제하며, 그 항목을 반환합니다.

i가 지정되지 않으면 마지막 항목을 삭제하고 되돌려줍니다.

# 변수명이 numbers인 리스트를 만들어봅시다.

numbers = [1, 2, 3, 4, 5, 6]
# pop 메서드로 가장 앞에 있는 숫자을 삭제해봅시다.
# 삭제 후 변수 numbers를 출력해봅시다.

print(numbers.pop(0))
print(numbers)
1
[2, 3, 4, 5, 6]
# pop 메서드로 가장 마지막에 있는 숫자를 삭제하고 결과를 변수 a 에 저장합니다.
# 삭제된 숫자와 결과를 모두 출력해봅시다.

a = numbers.pop()
print(f'{a}가 삭제되어 {numbers}가 되었습니다.')
6가 삭제되어 [2, 3, 4, 5]가 되었습니다.

.clear()

리스트의 모든 항목을 삭제합니다.

# 변수명이 numbers인 리스트를 만들어봅시다.
numbers = [1, 2, 3, 4, 5, 6]
# clear 메서드로 리스트의 모든 항목을 삭제합니다.

print(numbers)
numbers.clear()
print(numbers) # 단, 주소값은 유지
[1, 2, 3, 4, 5, 6]
[]

5.2.2 탐색 및 정렬

.index(x)

x 값을 찾아 해당 index 값을 반환합니다.

# 변수명이 a인 리스트를 만들어 봅시다.

a = [1, 2, 3, 4, 5]
# index 메서드로 숫자 3이 있는 위치를 반환합니다.

a.index(3)
2
# index 메서드로 숫자 100이 있는 위치를 확인해봅시다.
# index는 찾는 값이 없으면 오류가 발생합니다.

a.index(100)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_1184/1156058554.py in <module>
      2 # index는 찾는 값이 없으면 오류가 발생합니다.
      3 # =====
----> 4 a.index(100)

ValueError: 100 is not in list

.count(x)

원하는 값의 개수를 반환합니다.

# 변수명이 a인 리스트를 만들어 봅시다.

a = [1, 2, 5, 1, 5, 1]
# count 메서드로 1의 개수를 확인해봅시다.

a.count(1)
3
# 원하는 값을 모두 삭제하려면 다음과 같이 할 수 있습니다.

a = [1, 2, 1, 3, 4]
target_value = 1
for i in range(a.count(target_value)):
    a.remove(target_value)
print(a)
[2, 3, 4]

.sort()

정렬을 합니다.

내장함수 sorted() 와는 다르게 원본 list를 변형시키고, None을 리턴합니다.

# 변수 lotto에 1부터 45 까지의 숫자가 들어있는 리스트를 저장합니다.
# 6개의 숫자를 랜덤으로 저장합니다.

import random
lotto = random.sample(range(1, 46), 6)
print(lotto)
[11, 30, 23, 6, 42, 32]
# sort 메서드로 리스트를 정렬합니다.
# sort 메서드를 실행한 결과와 원본을 각각 출력해봅니다.

lotto.sort()
print(lotto.sort())
print(lotto)
None
[6, 11, 23, 30, 32, 42]
# sort 메서드의 reverse옵션을 이용하여 역순 정렬합니다.

lotto.sort(reverse=True)
print(lotto)
[42, 32, 30, 23, 11, 6]
# sorted 함수를 사용한 결과와 비교해봅시다.

import random
lotto = random.sample(range(1, 46), 6)
print(lotto, sorted(lotto))
[27, 33, 5, 36, 29, 25] [5, 25, 27, 29, 33, 36]

.reverse()

반대로 뒤집습니다. (정렬 아님)

# 변수 classroom에 이름이 여러개 있는 리스트를 저장합니다.

classroom = ['Tom', 'David', 'Justin']
print(classroom)
['Tom', 'David', 'Justin']
# reverse 메서드로 리스트를 역순으로 만들어줍니다.

classroom.reverse()
print(classroom)
['Justin', 'David', 'Tom']

5.2.3 리스트 복사

# 변수 original_list애 원본 리스트를 저장합니다.

original_list = [1, 2, 3]
# 변수 copy_list에 original_list를 저장하고 출력합니다.

copy_list = original_list
print(copy_list)
[1, 2, 3]
# copy_list의 첫번째 값을 5로 바꾸고 original_list를 출력해봅시다.

copy_list[0] = 5
print(original_list)
[5, 2, 3]
# copy_list, original_list 각각의 id 값을 == 연산자로 비교해봅시다.

id(copy_list) == id(original_list)
copy_list is original_list
True

데이터의 분류 (복습)

mutable vs. immutable

데이터는 크게 변경 가능한 것(mutable)들과 변경 불가능한 것(immutable)으로 나뉘며, python은 각각을 다르게 다룹니다.

변경 불가능한(immutable) 데이터
  • 리터럴(literal)

    • 숫자(Number)

    • 글자(String)

    • 참/거짓(Bool)

  • range()

  • tuple()

  • frozenset()

# immutable 데이터의 복사는 어떻게 이루어지는지 확인해봅시다

a = 20
b = a
b = 10

print(a)
print(b)
20
10
변경 가능한(mutable) 데이터
  • list

  • dict

  • set

# mutable 데이터의 복사는 어떻게 이루어지는지 확인해봅시다.

a = [1, 2, 3, 4]
b = a
b[0] = 100

print(a)
print(b)
[100, 2, 3, 4]
[100, 2, 3, 4]

리스트 복사 방법

slice 연산자 사용 [:]
# 변수명이 a인 리스트를 만들어봅시다.

a = [1, 2, 3]
# slice 연산자로 리스트 a의 모든 요소를 변수 b에 저장합니다.
# 리스트 b의 첫번째 값을 5로 바꾸고 리스트 a를 출력합니다.
# slice 연산자를 활용하면 새로운 리스트를 저장할 수 있습니다.

b = a[:]

b[0] = 5
print(a)
[1, 2, 3]
list() 활용
# 변수명이 a인 리스트를 만들어봅시다.

a = [1, 2, 3]
# list 함수로 리스트 a를 복사하여 변수 b에 저장합니다.
# 리스트 b의 첫번째 값을 5로 바꾸고 리스트 a를 출력합니다.

b = list(a)

b[0] = 5
print(a)
[1, 2, 3]
  • 하지만, 이렇게 하는 것도 일부 상황에만 서로 다른 얕은 복사(shallow copy)입니다.

# 변수명이 a인 2차원 리스트를 만들어봅시다.

a = [1, 2, [1, 2]]
# slice 연산자로 리스트 a의 모든 요소를 변수 b에 저장합니다.
# 리스트 b의 index 2번째 리스트의 첫번째 값을 5로 바꾸고 리스트 a를 출력합니다.

b = a[:]

b[2][0] = 5
print(a)
[1, 2, [5, 2]]
  • 만일 중첩된 상황에서 복사를 하고 싶다면, 깊은 복사(deep copy)를 해야합니다.

  • 즉, 내부에 있는 모든 객체까지 새롭게 값이 변경됩니다.

# 내부에 있는 리스트까지 복사를 하기위해서 copy 모듈을 활용합니다.

import copy

a = [1, 2, [1, 2]]
b = copy.deepcopy(a)

b[2][0] = 3
print(a)
[1, 2, [1, 2]]

5.2.4 List Comprehension

List Comprehension은 표현식과 제어문을 통해 리스트를 생성합니다.

여러 줄의 코드를 한 줄로 줄일 수 있습니다.

[expression for 변수 in iterable]

list(expression for 변수 in iterable)

[연습] 세제곱 리스트

다음의 리스트를 작성하세요.

  • 1~10까지의 숫자로 만든 세제곱 담긴 리스트 cubic_list

# 변수 numbers에 1부터 10까지의 숫자를 저장합니다.

numbers = range(1, 11)
# 반복문을 활용하여 작성합니다.

cubic_list = []
for number in numbers:
    cubic_list.append(number ** 3)

print(cubic_list)
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
# List comprehension을 활용하여 작성하세요.

cubic_list = [number**3 for number in numbers]

print(cubic_list)
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
# 10*10 matrix

[[0 for _ in range(10)] for _ in range(10)]
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

5.2.5 List Comprehension + 조건문

조건문에 참인 식으로 리스트를 생성합니다.

[expression for 변수 in iterable if 조건식]

[연습] 짝수리스트

다음의 리스트를 작성하세요.

  • 1~10까지의 숫자중 짝수만 담긴 리스트 even_list

  • 여러개의 for 혹은 if문을 중첩적으로 사용 가능합니다.

# 반복문을 활용하여 작성하세요.

even_list = []
for i in range(1, 11):
    if i % 2 == 0:
        even_list.append(i)

print(even_list)
[2, 4, 6, 8, 10]
# List comprehension을 활용하여 작성하세요.

even_list = [x for x in range(1, 11) if x % 2 == 0]
print(even_list)
[2, 4, 6, 8, 10]

[실습] 곱집합

주어진 두 list의 가능한 모든 조합을 담은 pair 리스트를 작성하세요.

  1. 반복문 활용

  2. list comprehension 활용

[입력 예시]

girls = ['jane', 'ashley', 'mary']
boys = ['justin', 'eric', 'david']

[출력 예시]

[('justin', 'jane'), ('justin', 'ashley'), ('justin', 'mary'), ('eric', 'jane'), ('eric', 'ashley'), ('eric', 'mary'), ('david', 'jane'), ('david', 'ashley'), ('david', 'mary')]
girls = ['jane', 'ashley', 'mary']
boys = ['justin', 'eric', 'david']
# 반복문을 활용하여 작성하세요.

pair = []
for boy in boys:
    for girl in girls:
        pair.append((boy, girl))

print(pair)
[('justin', 'jane'), ('justin', 'ashley'), ('justin', 'mary'), ('eric', 'jane'), ('eric', 'ashley'), ('eric', 'mary'), ('david', 'jane'), ('david', 'ashley'), ('david', 'mary')]
# List comprehension을 활용하여 작성하세요.

pair = [(boy, girl) for boy in boys for girl in girls]
print(pair)
[('justin', 'jane'), ('justin', 'ashley'), ('justin', 'mary'), ('eric', 'jane'), ('eric', 'ashley'), ('eric', 'mary'), ('david', 'jane'), ('david', 'ashley'), ('david', 'mary')]

[응용] 피타고라스 정리

주어진 조건(x < y < z < 50) 내에서 피타고라스 방정식의 해를 찾으세요.

  1. 반복문 활용

  2. list comprehension 활용


[출력 예시]

[(3, 4, 5), (5, 12, 13), (6, 8, 10), (7, 24, 25), (8, 15, 17), (9, 12, 15), (9, 40, 41), (10, 24, 26), (12, 16, 20), (12, 35, 37), (15, 20, 25), (15, 36, 39), (16, 30, 34), (18, 24, 30), (20, 21, 29), (21, 28, 35), (24, 32, 40), (27, 36, 45)]
# 반복문을 활용하여 작성하세요.

result = []
for x in range(1, 50):
    for y in range(x, 50):
        for z in range(y, 50):
            if x**2 + y**2 == z**2:
                result.append((x, y, z))

print(result)
[(3, 4, 5), (5, 12, 13), (6, 8, 10), (7, 24, 25), (8, 15, 17), (9, 12, 15), (9, 40, 41), (10, 24, 26), (12, 16, 20), (12, 35, 37), (15, 20, 25), (15, 36, 39), (16, 30, 34), (18, 24, 30), (20, 21, 29), (21, 28, 35), (24, 32, 40), (27, 36, 45)]
# List comprehension을 활용하여 작성하세요.

result = [(x, y, z) for x in range(1, 50) for y in range(x, 50) for z in range(y, 50) if x**2 + y**2 == z**2]
print(result)
[(3, 4, 5), (5, 12, 13), (6, 8, 10), (7, 24, 25), (8, 15, 17), (9, 12, 15), (9, 40, 41), (10, 24, 26), (12, 16, 20), (12, 35, 37), (15, 20, 25), (15, 36, 39), (16, 30, 34), (18, 24, 30), (20, 21, 29), (21, 28, 35), (24, 32, 40), (27, 36, 45)]

[응용] 모음 제거하기

다음의 문장에서 모음(a, e, i, o, u)를 모두 제거하세요.

[입력 예시]

words = 'Life is too short, you need python!'

[출력 예시]

Lf s t shrt, y nd pythn!
vowels = 'aeiou'
words = 'Life is too short, you need python!'
# 반복문을 활용하여 작성하세요.

result = []
for x in words:
    if x not in vowels:
        result.append(x)
        
print(''.join(result))
Lf s t shrt, y nd pythn!
# List comprehension을 활용하여 작성하세요.

result = [x for x in words if x not in vowels]
print(''.join(result))
Lf s t shrt, y nd pythn!

5.3 세트 (Set)

  • 중복 없이 순서가 없는 데이터 구조

  • 문자열의 특징

    • 변경 가능하고(mutable)

    • 순서가 없고(unordered)

    • 순회 가능한(iterable)

5.3.1 추가 및 삭제

.add(elem)

elem을 세트에 추가합니다.

# 변수명이 a인 세트를 만들어봅시다.

a = {'사과', '바나나', '수박'}
# add 메서드로 세트 a에 '포도'를 각각 2번 작성한 이후 세트 a를 출력해봅시다.

a.add('포도')
a.add('포도')
print(a)
{'바나나', '사과', '포도', '수박'}

.update(*others)

여러 값을 추가합니다.

인자로는 반드시 iterable 데이터 구조를 전달해야합니다.

# 변수명이 a인 세트를 만들어봅시다.

a = {'사과', '바나나', '수박'}
# update 메서드로 세트 a에 {'토마토', '토마토', '딸기'} 세트와 {'포도', '레몬'} 세트 인자 2개를 함께 입력 후 세트 a를 출력해봅시다.

a.update({'토마토', '토마토', '딸기'}, {'포도', '레몬'})
print(a)
{'바나나', '딸기', '사과', '포도', '수박', '레몬', '토마토'}

.remove(elem)

elem을 세트에서 삭제하고, 없으면 KeyError가 발생합니다.

# 변수명이 a인 세트를 만들어봅시다.

a = {'사과', '바나나', '수박'}
# remove 메서드로 세트 a에 '애플'과 '사과'를 각각 입력한 이후 세트 a를 출력해봅시다.

a.remove('애플')
a.remove('사과')
print(a)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9076/557948773.py in <module>
      1 # remove 메서드로 세트 a에 '애플'과 '사과'를 각각 입력한 이후 세트 a를 출력해봅시다.
      2 # =====
----> 3 a.remove('애플')
      4 a.remove('사과')
      5 print(a)

KeyError: '애플'

.discard(elem)

elem을 세트에서 삭제하고 없어도 에러가 발생하지 않습니다.

# 변수명이 a인 세트를 만들어봅시다.

a = {'사과', '바나나', '수박'}
# discard 메서드로 세트 a에 '포도'와 '수박'을 각각 입력한 이후 세트 a를 출력해봅시다.

a.discard('포도')
a.discard('수박')
print(a)
{'바나나', '사과'}

.pop()

임의의 원소를 제거해 반환합니다.

# 변수명이 a인 세트를 만들어봅시다.

a = {'사과', '바나나', '수박', '아보카도'}
# 세트 a에 pop 메서드를 사용 한 반환 값을 출력해봅시다.
# 이어서 세트 a만을 출력해봅시다.

print(a.pop())
print(a)
바나나
{'사과', '수박', '아보카도'}

5.4 딕셔너리(Dictionary)

  • Key와 Value로 구성된 데이터 구조

  • 딕셔너리의 특징

    • 변경 가능하고(mutable)

    • 순서가 없고(unordered)

    • 순회 가능한(iterable)

5.4.1 조회

.get(key[, default])

key를 통해 value를 가져옵니다.

절대로 KeyError가 발생하지 않습니다. default는 기본적으로 None입니다.

# 변수명이 my_dict인 딕셔너리를 만들어봅시다.

my_dict = {'apple': '사과', 'banana': '바나나', 'melon': '멜론'}
# get 메서드 없이 딕셔너리 my_dict의 key 'pineapple'의 value를 출력해봅시다.

my_dict['pineapple']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9076/1843533824.py in <module>
      1 # get 메서드 없이 딕셔너리 my_dict의 key 'pineapple'의 value를 출력해봅시다.
      2 # =====
----> 3 my_dict['pineapple']

KeyError: 'pineapple'
# get 메서드로 딕셔너리 my_dict의 key 'pineapple'의 value를 출력해봅시다.

print(my_dict.get('pineapple'))
None
# get 메서드로 딕셔너리 my_dict의 key 'apple'의 value를 출력해봅시다.

print(my_dict.get('apple'))
사과
# get 메서드로 딕셔너리 my_dict의 key 'pineapple'의 value를 출력해봅시다.
# 단, key가 없다면 0을 반환하도록 해봅시다.

print(my_dict.get('pineapple', 0))
0

5.4.2 추가 및 삭제

.pop(key[, default])

key가 딕셔너리에 있으면 제거하고 그 값을 돌려줍니다. 그렇지 않으면 default를 반환합니다.

default가 없는 상태에서 딕셔너리에 없으면 KeyError가 발생합니다.

# 변수명이 my_dict인 딕셔너리를 만들어봅시다.

my_dict = {'apple': '사과', 'banana': '바나나'}
# pop 메서드로 딕셔너리 my_dict의 key 'apple'을 제거해봅시다.
# 제거 후 딕셔너리 my_dict를 출력해봅시다.

my_dict.pop('apple')
print(my_dict)
{'banana': '바나나'}
# 제거하고자 하는 key가 딕셔너리에 없으면 KeyError가 발생합니다.
# 실행시켜 KeyError를 확인해봅시다.

my_dict.pop('melon')
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_11940/3531288252.py in <module>
      2 # 실행시켜 KeyError를 확인해봅시다.
      3 
----> 4 my_dict.pop('melon')

KeyError: 'melon'
# pop 메서드의 두번째 인자로 default 값을 설정 해 KeyError가 발생하지 않도록 할 수 있습니다.
# pop 메서드로 딕셔너리 my_dict의 key 'melon'을 제거하고 해당 key가 없다면 0을 반환하도록 해봅시다.

my_dict.pop('melon', 0)
0

.update()

값을 제공하는 key, value로 덮어씁니다.

# 변수명이 my_dict인 딕셔너리를 만들어봅시다.

my_dict = {'apple': '사과', 'banana': '바나나', 'melon': '멜론'}
# update 메서드로 딕셔너리 my_dict의 key는 'apple', value는 '사과아'를 입력해봅시다.

my_dict.update(apple='사과아')
# 딕셔너리 my_dict를 출력해봅시다.

print(my_dict)
{'apple': '사과아', 'banana': '바나나', 'melon': '멜론'}

5.4.3 딕셔너리 순회(반복문 활용)

딕셔너리에 for 문을 실행하면 기본적으로 다음과 같이 동작합니다.

# 딕셔너리를 반복문과 함께 사용해봅시다.
# 변수명이 grades인 딕셔너리를 만들어봅시다.

grades = {'john':  80, 'eric': 90, 'justin': 90}
# for문을 통해 딕셔너리 grades를 반복하면서 출력 값을 확인해봅시다.

for student in grades:
    print(student)
john
eric
justin

딕셔너리의 key를 접근할 수 있으면 value에도 접근할 수 있기 때문입니다.

따라서 딕셔너리의 value를 출력하기 위해서는 아래와 같이 작성합니다.

# 위에서 출력한 학생 이름(key)을 활용하여 점수(value)를 출력해봅시다.

for student in grades:
    print(grades[student])
80
90
90
  • dictionary에서 for를 활용하는 4가지 방법

# 0. dictionary 순회 (key 활용)
for key in dict:
    print(key)
    print(dict[key])


# 1. `.keys()` 활용
for key in dict.keys():
    print(key)
    print(dict[key])
    
    
# 2. `.values()` 활용
# 이 경우 key는 출력할 수 없음
for val in dict.values():
    print(val)

    
# 3. `.items()` 활용
for key, val in dict.items():
    print(key, val)

# 아래의 grades를 활용하여 4가지 반복문을 직접 작성해봅시다.

grades = {'john':  80, 'eric': 90, 'justin': 90}

for student in grades:
    print(student, grades[student])
    
for student in grades.keys():
    print(student, grades[student])
    
for grade in grades.values():
    print(grade)

for student, grade in grades.items():
    print(student, grade)
john 80
eric 90
justin 90
john 80
eric 90
justin 90
80
90
90
john 80
eric 90
justin 90

[연습] 딕셔너리 순회

혈액형 검사한 결과가 담긴 blood_types이 주어졌을때, 해당 딕셔너리를 순회하며, keyvalue를 출력해보세요.


[출력 예시]

A형은 40명입니다.
B형은 11명입니다.
AB형은 4명입니다.
O형은 45명입니다.
# 변수명이 blood_types인 딕셔너리를 만들어봅시다.

blood_types = {'A': 40, 'B': 11, 'AB': 4, 'O': 45}
# for문을 활용해봅시다.
# 딕셔너리 blood_types을 순회하며,
# 아래와 같은 문장이 출력되도록 하는 코드를 작성하세요.
"""
A형은 40명입니다.
B형은 11명입니다.
AB형은 4명입니다.
O형은 45명입니다.
"""

for blood_type in blood_types:
    print(f'{blood_type}형은 {blood_types[blood_type]}명입니다.')
A형은 40명입니다.
B형은 11명입니다.
AB형은 4명입니다.
O형은 45명입니다.
# keys메서드를 활용해봅시다.
# blood_types.keys()을 순회하며,
# 아래와 같은 문장이 출력되도록 하는 코드를 작성하세요.

"""
A형은 40명입니다.
B형은 11명입니다.
AB형은 4명입니다.
O형은 45명입니다.
"""

for blood_type in blood_types.keys():
    print(f'{blood_type}형은 {blood_types[blood_type]}명입니다.')
A형은 40명입니다.
B형은 11명입니다.
AB형은 4명입니다.
O형은 45명입니다.
# items 메서드를 활용해봅시다.
# blood_types.items()을 순회하며,
# 아래와 같은 문장이 출력되도록 하는 코드를 작성하세요.
"""
A형은 40명입니다.
B형은 11명입니다.
AB형은 4명입니다.
O형은 45명입니다.
"""

for blood_type, number in blood_types.items():
    print(f'{blood_type}형은 {number}명입니다.')
A형은 40명입니다.
B형은 11명입니다.
AB형은 4명입니다.
O형은 45명입니다.

[실습] 딕셔너리 순회

혈액형 검사한 결과가 담긴 blood_types이 주어졌을때, 해당 검사에 참가한 사람들의 총합을 구해보세요.


[출력 예시]

검사에 참가한 사람은  100명입니다.
# 변수명이 blood_types인 딕셔너리를 만들어봅시다.

blood_types = {'A': 40, 'B': 11, 'AB': 4, 'O': 45}
# for문을 통해 딕셔너리 blood_types를 순회하며,
# dict[key]로 접근하는 방법을 통해
# '검사에 참가한 사람은 총 100명입니다.' 라는 문장을 출력하는 코드를 작성하세요.

total = 0
for blood_type in blood_types:
    total += blood_types[blood_type]
print(f'검사에 참가한 사람은 총 {total}명입니다.')
검사에 참가한 사람은 총 100명입니다.
# 메서드 values를 활용해봅시다.
# for문을 통해 딕셔너리 blood_types를 순회하며,
# '검사에 참가한 사람은 총 100명입니다.' 라는 문장을 출력하는 코드를 작성하세요.

total = 0
for number in blood_types.values():
    total += number
print(f'검사에 참가한 사람은 총 {total}명입니다.')
검사에 참가한 사람은 총 100명입니다.
# 빌트인 함수 sum을 사용해 
# '검사에 참가한 사람은 총 100명입니다.' 라는 문장을 출력하는 코드를 간단하게 작성해보세요.

total = sum(blood_types.values())
print(f'검사에 참가한 사람은 총 {total}명입니다.')
검사에 참가한 사람은 총 100명입니다.

[응용] 딕셔너리 구축하기(counter)

리스트가 주어질 때, 각각의 요소의 개수를 value 값으로 갖는 딕셔너리를 만드세요.


[출력 예시]

{‘great’: 2, ‘expectations’: 1, ‘the’: 2, ‘adventures’: 2, ‘of’: 2, ‘sherlock’: 1, ‘holmes’: 1, ‘gasby’: 1, ‘hamlet’: 1, ‘huckleberry’: 1, ‘fin’: 1}

# 변수명이 book_title인 리스트를 만들어봅시다.

book_title =  ['great', 'expectations', 'the', 'adventures', 'of', 'sherlock', 'holmes', 'the', 'great', 'gasby', 'hamlet', 'adventures', 'of', 'huckleberry', 'fin']
# 1. dict[key]로 접근하는 방법을 통해 작성해보세요.

title_counter = {}
for title in book_title:
    if title in title_counter:
        title_counter[title] += 1
    else:
        title_counter[title] = 1
        
print(title_counter)
{'great': 2, 'expectations': 1, 'the': 2, 'adventures': 2, 'of': 2, 'sherlock': 1, 'holmes': 1, 'gasby': 1, 'hamlet': 1, 'huckleberry': 1, 'fin': 1}
# 2. count 메서드를 활용해 작성해보세요.

title_counter = {}
for title in book_title:
    title_counter[title] = book_title.count(title)

print(title_counter)
{'great': 2, 'expectations': 1, 'the': 2, 'adventures': 2, 'of': 2, 'sherlock': 1, 'holmes': 1, 'gasby': 1, 'hamlet': 1, 'huckleberry': 1, 'fin': 1}
# 3. get 메서드를 활용해 작성해보세요.

title_counter = {}
for title in book_title:
    title_counter[title] = title_counter.get(title, 0) + 1

print(title_counter)
{'great': 2, 'expectations': 1, 'the': 2, 'adventures': 2, 'of': 2, 'sherlock': 1, 'holmes': 1, 'gasby': 1, 'hamlet': 1, 'huckleberry': 1, 'fin': 1}

get(key[, default])

  • key 가 딕셔너리에 있는 경우 key 에 대응하는 값을 돌려주고, 그렇지 않으면 default 를 돌려줍니다.

sonnets = """
From fairest creatures we desire increase,
That thereby beauty’s rose might never die,
But as the riper should by time decrease,
His tender heir mught bear his memeory:
But thou, contracted to thine own bright eyes,
Feed’st thy light’st flame with self-substantial fuel,
Making a famine where abundance lies,
Thyself thy foe, to thy sweet self too cruel.
Thou that art now the world’s fresh ornament
And only herald to the gaudy spring,
Within thine own bud buriest thy content
And, tender churl, makest waste in niggarding.
Pity the world, or else this glutton be,
To eat the world’s due, by the grave and thee.
"""

sonnets = sonnets.replace(',', '').replace('\n', ' ').lower().split()

sonnet_counter = {}
for title in sonnets:
    if title in sonnet_counter:
        sonnet_counter[title] += 1
    else:
        sonnet_counter[title] = 1
        
sonnet_counter
{'from': 1,
 'fairest': 1,
 'creatures': 1,
 'we': 1,
 'desire': 1,
 'increase': 1,
 'that': 2,
 'thereby': 1,
 'beauty’s': 1,
 'rose': 1,
 'might': 1,
 'never': 1,
 'die': 1,
 'but': 2,
 'as': 1,
 'the': 6,
 'riper': 1,
 'should': 1,
 'by': 2,
 'time': 1,
 'decrease': 1,
 'his': 2,
 'tender': 2,
 'heir': 1,
 'mught': 1,
 'bear': 1,
 'memeory:': 1,
 'thou': 2,
 'contracted': 1,
 'to': 4,
 'thine': 2,
 'own': 2,
 'bright': 1,
 'eyes': 1,
 'feed’st': 1,
 'thy': 4,
 'light’st': 1,
 'flame': 1,
 'with': 1,
 'self-substantial': 1,
 'fuel': 1,
 'making': 1,
 'a': 1,
 'famine': 1,
 'where': 1,
 'abundance': 1,
 'lies': 1,
 'thyself': 1,
 'foe': 1,
 'sweet': 1,
 'self': 1,
 'too': 1,
 'cruel.': 1,
 'art': 1,
 'now': 1,
 'world’s': 2,
 'fresh': 1,
 'ornament': 1,
 'and': 3,
 'only': 1,
 'herald': 1,
 'gaudy': 1,
 'spring': 1,
 'within': 1,
 'bud': 1,
 'buriest': 1,
 'content': 1,
 'churl': 1,
 'makest': 1,
 'waste': 1,
 'in': 1,
 'niggarding.': 1,
 'pity': 1,
 'world': 1,
 'or': 1,
 'else': 1,
 'this': 1,
 'glutton': 1,
 'be': 1,
 'eat': 1,
 'due': 1,
 'grave': 1,
 'thee.': 1}

5.4.4 Dictionary comprehension

dictionary도 comprehension을 활용하여 만들 수 있습니다.

iterable에서 dict를 생성할 수 있습니다.

{:  for 요소 in iterable}

dict({:  for 요소 in iterable})
# for문과 range 함수를 통해 1~8까지의 숫자를 반복하며,
# key는 각 숫자, value는 각 숫자를 3제곱하는 값이 되도록하는 딕셔너리 cubic을
# Dictionary comprehension를 사용해 작성하세요.

cubic = {x: x ** 3 for x in range(1, 8)}
print(cubic)
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216, 7: 343}
# 변수명이 blood_types인 딕셔너리를 만들어봅시다.

blood_types = {'A': 40, 'B': 11, 'AB': 4, 'O': 45}
# blood_types을 통해
# 아래와 같은 값을 가지는 딕셔너리 negative_blood_types를 생성하는 코드를
# Dictionary comprehension를 사용해 작성하세요.
"""
{'-A': 40, '-B': 11, '-AB': 4, '-O': 45}
"""

negative_blood_types = {'-' + key: value for key, value in blood_types.items()}
# negative_blood_types = {'-' + key: blood_types[key] for key in blood_types}
print(negative_blood_types)
{'-A': 40, '-B': 11, '-AB': 4, '-O': 45}

5.4.5 Dictionary comprehension + 조건

List comprehension과 유사하게, 조건문에 참인 식으로 딕셔너리를 생성합니다.

{:  for 요소 in iterable if 조건식}
# 변수명이 dusts인 딕셔너리를 만들어봅시다.

dusts = {'서울': 72, '인천': 82, '제주': 29, '동해': 45}
# dusts을 통해
# 미세먼지 농도가 80 초과 지역 값을 가진 딕셔너리 result를 생성하는 코드를
# Dictionary comprehension + 조건문을 사용해 작성하세요.
"""
출력 결과)

{'인천': 82}
"""

result = {key: value for key, value in dusts.items() if value > 80}
print(result)
{'인천': 82}
# dusts을 통해
# 미세먼지 농도가 80초과는 나쁨, 80이하는 보통으로 하는 value를 가지도록 하는 딕셔너리 result를 생성하는 코드를
# Dictionary comprehension + 조건문을 사용해 작성하세요.
"""
출력 결과)

{'서울': '보통', '인천': '나쁨', '제주': '보통', '동해': '보통'}
"""

result = {key: '나쁨' if value > 80 else '보통' for key, value in dusts.items()}
print(result)
{'서울': '보통', '인천': '나쁨', '제주': '보통', '동해': '보통'}
# Dictionary comprehension에서 if-else도 열거할 수 있습니다.
# dusts을 통해
# 미세먼지 농도가 150초과는 '매우나쁨', 80초과는 '나쁨', 30초과는 '보통', 30이하는 '좋음'으로 하는 value를 가지도록 하는 
# 딕셔너리 result를 생성하는 코드를
# Dictionary comprehension + 조건문을 사용해 작성하세요.

result = {key: '매우나쁨' if value > 150 else '나쁨' if value > 80 else '보통' if value > 30 else '좋음' for key, value in dusts.items()}
print(result)
{'서울': '보통', '인천': '나쁨', '제주': '좋음', '동해': '보통'}

5.5 데이터 구조에 적용가능한 Built-in Function

순회 가능한(iterable) 데이터 구조에 적용가능한 Built-in Function

iterable 타입 - list, dict, set, str, bytes, tuple, range

  • map()

  • filter()

  • zip()

  • ~~reduce()~~ (참고)

map(function, iterable)

  • 순회가능한 데이터 구조(iterable)의 모든 요소에 function을 적용한 후 그 결과를 돌려준다.

  • return은 map_object 형태이다.

numbers = [1, 2, 3]
# 위의 변수 numbers를 문자열 '123'으로 만드세요. (join 메서드 활용)
# List comprehension 활용

new_numbers = ''.join([str(num) for num in numbers])
print(new_numbers)
123
# map() 활용

new_numbers = map(str, numbers)
print(new_numbers)
print(''.join(new_numbers))
<map object at 0x0000019C153D5940>
123
print(new_numbers)
<map object at 0x0000019C153D5940>

map() 함수는 입력값을 처리할 때 자주 활용됩니다.

numbers = ['1', '2', '3']
# 위의 변수 numbers를 정수로 구성된 리스트 [1, 2, 3]으로 만드세요.
# List comprehension 활용

new_numbers = [int(num) for num in numbers]
print(new_numbers)
[1, 2, 3]
# map() 활용

new_numbers = map(int, numbers)
new_numbers = list(map(int, numbers))

print(new_numbers)
[1, 2, 3]

첫번째 인자 function은 사용자 정의 함수도 가능합니다.

# 세제곱의 결과를 나타내는 함수가 있습니다.

def cube(n):
    return n ** 3
# 세제곱 함수를 각각의 요소에 적용한 결과값을 구해봅시다.

numbers = [1, 2, 3]
map_numbers = map(cube, numbers)
new_numbers = list(map_numbers)

# 맵은 일회용이므로 list로 소비되면 사라집니다. (generator)

print(new_numbers)
list(map_numbers)
[1, 8, 27]
[]

[연습] 코딩 테스트의 기본

두 정수를 입력 받아 더한 값을 출력하시오.

[입력 예시]

3 5


[출력 예시]

8

# 아래에 코드를 작성하시오.
# =====
numbers = map(int, input().split())
total = 0
for number in numbers:
    total += number
print(total)
 3 5
8

filter(function, iterable)

  • iterable에서 function의 반환된 결과가 True 인 것들만 구성하여 반환합니다.

  • filter object 를 반환합니다.

# 특정 list에서 홀수만을 걸러내는 코드를 작성해봅시다.
# 홀수를 판별하는 함수가 있습니다.

def odd(n):
    return n % 2
# 홀수인 요소만 뽑아 new_numbers에 저장합니다.

numbers = [1, 2, 3]
new_numbers = list(filter(odd, numbers))

print(new_numbers)
[1, 3]
# 다음의 list comprehension과 동일합니다.

[x for x in numbers if odd(x)]
[x for x in numbers if x % 2 ]
[1, 3]
movies = [
    {'id': 1, 'title': 'matrix', 'adult': False},
    {'id': 2, 'title': '타짜', 'adult': True},
    {'id': 3, 'title': '랑종', 'adult': True},
    {'id': 4, 'title': '크루엘라', 'adult': False},
]

def is_adult_movie(movie):
    return movie['adult']

adult_movies = list(filter(is_adult_movie, movies))
print(adult_movies)
[{'id': 2, 'title': '타짜', 'adult': True}, {'id': 3, 'title': '랑종', 'adult': True}]
adult_movies = list(filter(lambda movie: movie['adult'], movies))
print(adult_movies)
[{'id': 2, 'title': '타짜', 'adult': True}, {'id': 3, 'title': '랑종', 'adult': True}]

zip(*iterables)

  • 복수의 iterable 객체를 모아(zip())줍니다.

  • 결과는 튜플의 모음으로 구성된 zip object 를 반환합니다.

girls = ['jane', 'ashley', 'mary']
boys = ['justin', 'eric', 'david']
# zip() 활용하여 짝을 맞추어 본다.

pair = list(zip(girls, boys))
print(pair)
[('jane', 'justin'), ('ashley', 'eric'), ('mary', 'david')]