{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## 02-1 숫자형\n", "\n", "- 숫자형(Number): 숫자 형태로 이루어진 자료형\n", "\n", "| 항목 | 사용 예 |\n", "|:---:|:---:|\n", "| 정수 | 123, -345, 0 |\n", "| 실수 | 123.45, -1234.5, 3.4e10 |\n", "| 8진수 | 0o34, 0o25 |\n", "| 16진수 | 0x2A, 0xFF |\n", "\n", "### 숫자형을 활용하기 위한 연산자" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "7\n", "12\n", "0.75\n" ] } ], "source": [ "# 사칙연산\n", "\n", "a = 3\n", "b = 4\n", "\n", "print(a+b)\n", "print(a*b)\n", "print(a/b)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "81\n", "1\n", "3\n", "1\n", "-2\n" ] } ], "source": [ "# 제곱 ** 연산자\n", "\n", "a = 3\n", "b = 4\n", "print(a**b)\n", "\n", "# 나눗셈 후 나머지를 반환하는 % 연산자\n", "\n", "print(7%3)\n", "print(3%7)\n", "\n", "# 나눗셈 후 소수점 아랫자리를 버리는 // 연산자\n", "\n", "print(7//4)\n", "print(-7//4) # 무조건 소수점을 버리는 것이 아니라 나눗셈의 결과값보다 작은 정수 중, 가장 큰 정수를 리턴한다." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## 02-2 문자열 자료형\n", "\n", "- 문자열(String): 문자, 단어 등으로 구성된 문자들의 집합\n", " - \"Life is too short, You need Python\"\n", " - \"a\"\n", " - \"123\"\n", " \n", "### 문자열은 어떻게 만들고 사용할까?\n", "\n", "파이썬에서 문자열을 만드는 4가지 방법\n", "\n", "1. 큰따옴표로 양쪽 둘러싸기: \"Hello World\"\n", "2. 작은따옴표로 양쪽 둘러싸기: 'Python is fun'\n", "3. 큰따옴표 3개를 연속으로 써서 양쪽 둘러싸기: \"\"\"Life is too short, You need python\"\"\"\n", "4. 작은따옴표 3개를 연속으로 써서 양쪽 둘러싸기: '''Life is too short, You need python'''\n", "\n", "### 문자열 안에 작은따옴표나 큰따옴표를 포함시키고 싶을 때\n", "\n", "1) 문자열에 작은따옴표(') 포함시키기: Python's favorite food is perl\n", "\n", " 다음과 같이 문자열을 큰따옴표(\")로 둘러싸야 한다.\n", "\n", "```python\n", ">>> food = \"Python's favorite food is perl\"\n", "```\n", "\n", "2) 문자열에 큰따옴표(\") 포함시키기: \"Python is very easy.\" he says.\n", "\n", " 다음과 같이 문자열을 작은따옴표(')로 둘러싸야 한다.\n", " \n", "```python\n", ">>> sqy = '\"Python is very easy.\" he says.'\n", "```\n", "\n", "3) \\ (백슬래시)를 이용해서 작은따옴표(')와 큰따옴표(\")를 문자열에 포함시키기\n", "\n", "```python\n", ">>> food = 'Python\\'s favorite food is perl'\n", ">>> say = \"\\\"Python is very easy.\\\" he says.\"\n", "```\n", "\n", "### 여러 줄인 문자열을 변수에 대입하고 싶을 때\n", "\n", "1) 줄을 바꾸기 위한 이스케이프 코드 \\n 삽입하기\n", "```\n", ">>> multiline = \"Life is too short \\n You need python\"\n", "```\n", "\n", "2) 연속된 작은따옴표 3개(''') 또는 큰따옴표 3개(\"\"\") 이용\n", "```\n", ">>> multiline = '''\n", "Life is too short\n", "You need python\n", "'''\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "\n", "### 문자열 연산하기\n", "\n", "#### 1) 문자열 더해서 연결하기(Concatenation)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Python is fun!'" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "head = \"Python\"\n", "tail = \" is fun!\"\n", "\n", "head + tail" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 2) 문자열 곱하기" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'pythonpython'" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = \"python\"\n", "a * 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 3) 문자열 곱하기 응용" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "==================================================\n", "My Program\n", "==================================================\n" ] } ], "source": [ "print(\"=\" * 50)\n", "print(\"My Program\")\n", "print(\"=\" * 50)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "\n", "### 문자열 인덱싱과 슬라이싱\n", "\n", "#### 문자열 인덱싱이란?\n", "\n", "*\"파이썬은 0부터 숫자를 센다.\"*" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'e'" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = \"Life is too short, You need Python\"\n", "a[3]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 문자열 인덱싱 활용하기" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "o\n", "y\n" ] } ], "source": [ "print(a[-2])\n", "print(a[-5])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 문자열 슬라이싱이란?" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Life'" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b = a[0] + a[1] + a[2] + a[3]\n", "b" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Life'" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a[0:4]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 문자열을 슬라이싱하는 방법" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Li\n", "is\n", "short\n" ] } ], "source": [ "print(a[0:2])\n", "print(a[5:7])\n", "print(a[12:17])" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'You need Python'" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a[19:]" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Life is too short'" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a[:17]" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Life is too short, You need Python'" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a[:]" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'You need'" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a[19:-7]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 슬라이싱으로 문자열 나누기" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "20010331\n", "Rainy\n" ] } ], "source": [ "a = \"20010331Rainy\"\n", "date = a[:8]\n", "weather = a[8:]\n", "\n", "print(date)\n", "print(weather)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2001\n", "0331\n", "Rainy\n" ] } ], "source": [ "year = a[:4]\n", "day = a[4:8]\n", "weather = a[8:]\n", "\n", "print(year)\n", "print(day)\n", "print(weather)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### [\"Pithon\" 이라는 문자열을 \"Python\" 으로 바꾸려면?]" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'i'" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = \"Pithon\"\n", "a[1]" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'str' object does not support item assignment", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0ma\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m'y'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: 'str' object does not support item assignment" ] } ], "source": [ "a[1] = 'y'" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Python'" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a[:1] + 'y' + a[2:]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "### 문자열 포매팅\n", "\n", "#### 문자열 포매팅 따라하기\n" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'I eat 3 apples.'" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"I eat %d apples.\" % 3" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'I eat five apples.'" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"I eat %s apples.\" % \"five\"" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'I eat 3 apples.'" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "number = 3\n", "\"I eat %d apples.\" % number" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'I ate 10 apples. so I was sick for three days.'" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "number = 10\n", "day = \"three\"\n", "\"I ate %d apples. so I was sick for %s days.\" % (number, day)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 문자열 포맷 코드\n", "\n", "| 코드 | 설명 |\n", "|:---:|:---:|\n", "| %s | 문자열(String) |\n", "| %c | 문자 1개(character) |\n", "| %d | 정수(Integer) |\n", "| %f | 부동소수(floating-point) |\n", "| %o | 8진수 |\n", "| %x | 16진수 |\n", "| %% | Literal % (문자 % 자체) |" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "ename": "ValueError", "evalue": "incomplete format", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;34m\"Error is %d%\"\u001b[0m \u001b[0;34m%\u001b[0m \u001b[0;36m98\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mValueError\u001b[0m: incomplete format" ] } ], "source": [ "\"Error is %d%\" % 98" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Error is 98%'" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"Error is %d%%\" % 98" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 포맷코드와 숫자 함께 사용하기" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' hi'" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 정렬과 공백\n", "\n", "\"%10s\" % \"hi\"" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'hi jane'" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"%-10s jane\" % \"hi\"" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'3.4213'" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 소수점 표현하기\n", "\n", "\"%0.4f\" % 3.42134234" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' 3.4213'" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"%10.4f\" % 3.42134234" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "### 문자열 관련 함수들\n", "\n", "- 문자열 내장함수: 문자열 자료형은 자체적으로 가지고 있는 함수들이 있다." ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 문자 개수 세기(count)\n", "\n", "a = \"hobby\"\n", "a.count('b')" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10\n", "-1\n" ] } ], "source": [ "# 위치 알려주기 1(find)\n", "\n", "a = \"Python is best choice\"\n", "\n", "print(a.find('b'))\n", "print(a.find('k'))" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8\n" ] }, { "ename": "ValueError", "evalue": "substring not found", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mindex\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m't'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 6\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mindex\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'k'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mValueError\u001b[0m: substring not found" ] } ], "source": [ "# 위치 알려주기 2(index)\n", "\n", "a = \"Life is too short\"\n", "\n", "print(a.index('t'))\n", "print(a.index('k'))" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'a,b,c,d'" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 문자열 삽입(join)\n", "\n", "a = ','\n", "a.join('abcd')" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "HI\n", "hi\n" ] } ], "source": [ "# 소문자를 대문자로 바꾸기(upper)\n", "\n", "a = \"hi\"\n", "print(a.upper())\n", "\n", "# 대문자를 소문자로 바꾸기(lower)\n", "\n", "a = \"HI\"\n", "print(a.lower())" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'hi '" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 왼쪽 공백 지우기(lstrip)\n", "\n", "a = \" hi \"\n", "a.lstrip()" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' hi'" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 오른쪽 공백 지우기(rstrip)\n", "a.rstrip()" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'hi'" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 양쪽 공백 지우기(strip)\n", "a.strip()" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Your leg is too short'" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 문자열 바꾸기(replace)\n", "\n", "a = \"Life is too short\"\n", "a.replace(\"Life\", \"Your leg\")" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['Life', 'is', 'too', 'short']" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 문자열 나누기(split)\n", "\n", "a = \"Life is too short\"\n", "a.split()" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a', 'b', 'c', 'd']" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = \"a:b:c:d\"\n", "a.split(\":\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "### [고급 문자열 포매팅]" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'I eat 3 apples'" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 숫자 바로 대입하기\n", "\n", "\"I eat {0} apples\".format(3)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'I eat five apples'" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 문자열 바로 대입하기\n", "\n", "\"I eat {0} apples\".format(\"five\")" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'I eat 3 apples'" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 숫자 값을 가진 변수로 대입하기\n", "\n", "number = 3\n", "'I eat {0} apples'.format(number)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'I ate 10 apples. so I was sick for three days.'" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 2개 이상의 값 넣기\n", "\n", "number = 10\n", "day = \"three\"\n", "\"I ate {0} apples. so I was sick for {1} days.\".format(number, day)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'I ate 10 apples. so I was sick for 3 days.'" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 이름으로 넣기\n", "\n", "\"I ate {number} apples. so I was sick for {day} days.\".format(number=10, day=3)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'I ate 10 apples. so I was sick for 3 days.'" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 인덱스와 이름을 혼용해서 넣기\n", "\n", "\"I ate {0} apples. so I was sick for {day} days.\".format(10, day=3)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'hi '" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 왼쪽 정렬\n", "\n", "\"{0:<10}\".format(\"hi\")" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' hi'" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 오른쪽 정렬\n", "\n", "\"{0:>10}\".format(\"hi\")" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' hi '" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 가은데 정렬\n", "\n", "\"{0:^10}\".format(\"hi\")" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'====hi===='" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 공백 채우기\n", "\n", "\"{0:=^10}\".format(\"hi\")" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'hi!!!!!!!!'" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"{0:!<10}\".format(\"hi\")" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'3.4213'" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 소수점 표현하기\n", "\n", "y = 3.42134234\n", "\"{0:0.4f}\".format(y)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' 3.4213'" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"{0:10.4f}\".format(y)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'{ and }'" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# { 또는 } 문자 표현하기\n", "\n", "\"{{ and }}\".format()" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "---\n", "## 02-3 리스트 자료형\n", "\n", "### 리스트는 어떻게 만들고 사용할까?\n", "\n", "```\n", ">>> odd = [1, 3, 5, 7, 9]\n", "\n", ">>> a = [ ]\n", ">>> b = [1, 2, 3]\n", ">>> c = ['Life', 'is', 'too', 'short']\n", ">>> d = [1, 2, 'Life', 'is']\n", ">>> e = [1, 2, ['Life', 'is']]\n", "```\n", "\n", "- 비어있는 리스트는 a = list() 로 생성할 수도 있다." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 리스트의 인덱싱과 슬라이싱\n", "\n", "- 리스트도 문자열처럼 인덱싱과 슬라이싱이 가능하다.\n", "\n", "#### 리스트의 인덱싱" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [1, 2, 3]\n", "\n", "a[0]" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a[0] + a[2]" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a[-1]" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [1, 2, 3, ['a', 'b', 'c']]\n", "\n", "a[0]" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a', 'b', 'c']" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a[-1]" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a', 'b', 'c']" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a[3]" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'a'" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a[-1][0]" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'b'" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a[-1][1]" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "#### 리스트의 슬라이싱" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2]" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [1, 2, 3, 4, 5]\n", "a[0:2]" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2]" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a[:2]" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[3, 4, 5]" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a[2:]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "### 리스트 연산자\n", "\n", "#### 1) 리스트 더하기(+)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4, 5, 6]" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [1, 2, 3]\n", "b = [4, 5, 6]\n", "\n", "a + b" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 2) 리스트 반복하기(*)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 1, 2, 3, 1, 2, 3]" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [1, 2, 3]\n", "\n", "a * 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "### 리스트의 수정, 변경과 삭제\n", "\n", "#### 1. 리스트에서 하나의 값 수정하기" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 4]" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [1, 2, 3]\n", "a[2] = 4\n", "\n", "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 2. 리스트에서 연속된 범위의 값 수정하기" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[2]" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a[1:2]" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 'a', 'b', 'c', 4]" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a[1:2] = [\"a\", \"b\", \"c\"]\n", "\n", "a" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, ['a', 'b', 'c'], 'b', 'c', 4]" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a[1] = ['a', 'b', 'c']\n", "\n", "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 3. [] 사용해 리스트 요소 삭제하기" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 'c', 4]" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a[1:3] = []\n", "\n", "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 4. del 함수 사용해 리스트 요소 삭제하기" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 'c', 4]" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 4]" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "del a[1]\n", "\n", "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "### 리스트 관련 함수들\n", "\n", "#### 리스트에 요소 추가(append)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4]" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [1, 2, 3]\n", "a.append(4)\n", "\n", "a" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4, [5, 6]]" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.append([5, 6])\n", "\n", "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 리스트 정렬(sort)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4]" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [1, 4, 3, 2]\n", "a.sort()\n", "\n", "a" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a', 'b', 'c']" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = ['a', 'c', 'b']\n", "a.sort()\n", "\n", "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 리스트 뒤집기(reverse)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['b', 'c', 'a']" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = ['a', 'c', 'b']\n", "a.reverse()\n", "\n", "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 위치 반환(index)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [1, 2, 3]\n", "a.index(3)" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.index(1)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "ename": "ValueError", "evalue": "0 is not in list", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0ma\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mindex\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mValueError\u001b[0m: 0 is not in list" ] } ], "source": [ "a.index(0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 리스트에 요소 삽입(insert)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[4, 1, 2, 3]" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [1, 2, 3]\n", "a.insert(0, 4)\n", "\n", "a" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[4, 1, 2, 5, 5, 3]" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.insert(3, 5)\n", "\n", "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 리스트 요소 제거(remove)" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 1, 2, 3]" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [1, 2, 3, 1, 2, 3]\n", "a.remove(3) # 첫번째 3만 제거됨\n", "\n", "a" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 1, 2]" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.remove(3)\n", "\n", "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 리스트 요소 끄집어 내기(pop)" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# pop()은 리스트의 맨 마지막 요소를 돌려주고 해당 요소는 삭제함\n", "\n", "a = [1, 2, 3]\n", "a.pop()" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2]" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [1, 2, 3]\n", "a.pop(1)" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 3]" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 리스트에 포함된 요소 x의 개수 세기(count)" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [1, 2, 3, 1]\n", "\n", "a.count(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 리스트 확장(extend)" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4, 5]" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# extend(x)에서 x에는 리스트만 올 수 있다.\n", "\n", "a = [1, 2, 3]\n", "a.extend([4, 5])\n", "\n", "a" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4, 5, 6, 7]" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b = [6, 7]\n", "a.extend(b)\n", "\n", "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- a.extend([4, 5])는 a += [4, 5] 와 동일하다" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "---\n", "## 02-4 튜플 자료형\n", "\n", "### 튜플은 어떻게 만들까?\n", "\n", "튜플(tuple)은 리스트와 거의 비슷하지만, 다른 점은 다음과 같다.\n", "\n", "- 리스트는 [ 과 ] 으로 둘러싸지만 튜플은 ( 과 ) 으로 둘러싼다.\n", "- 리스트는 그 값의 생성, 삭제, 수정이 가능하지만 **튜플은 그 값을 바꿀 수 없다.**\n", "\n", "```\n", ">>> t1 = ()\n", ">>> t2 = (1,) # 단지 1개의 요소만을 가질 때에도 요소 뒤에 콤마(,)를 반드시 붙여야 한다.\n", ">>> t3 = (1, 2, 3)\n", ">>> t4 = 1, 2, 3 # 괄호()를 생략해도 무방하다.\n", ">>> t5 = ('a', 'b', ('ab', 'cd'))\n", "```\n", "\n", "#### 튜플 요소값 삭제 또는 변경 시 오류" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'tuple' object doesn't support item deletion", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mt1\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'a'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'b'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32mdel\u001b[0m \u001b[0mt1\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: 'tuple' object doesn't support item deletion" ] } ], "source": [ "t1 = (1, 2, 'a', 'b')\n", "del t1[0]" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'tuple' object does not support item assignment", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mt1\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m'c'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: 'tuple' object does not support item assignment" ] } ], "source": [ "t1[0] = 'c'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "### 튜플의 인덱싱과 슬라이싱, 더하기(+)와 곱하기(*)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 인덱싱하기\n", "\n", "t1 = (1, 2, 'a', 'b')\n", "t1[0]" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'b'" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "t1[3]" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(2, 'a', 'b')" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 슬라이싱하기\n", "\n", "t1[1:]" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(1, 2, 'a', 'b', 3, 4)" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 튜플 더하기\n", "\n", "t2 = (3, 4)\n", "\n", "t1 + t2" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(3, 4, 3, 4, 3, 4)" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 튜플 곱하기\n", "\n", "t2 * 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## 02-5 딕셔너리 자료형\n", "\n", "- 딕셔너리(Dictionary) 자료형: key 와 value 를 한쌍으로 갖는 자료형\n", "- 대응 관계를 나타내는 자료형으로 연관 배열(Associative array) 또는 해시(Hash)라고도 한다.\n", "- 리스트나 튜플처럼 순차적으로 요소에 접근하는 것이 아니고, key를 통해 value를 얻는다.\n", "- 순서를 따지지 않는다.\n", "\n", "### 딕셔너리는 어떻게 만들까?\n", "\n", "- {Key1:Value1, Key2:Value2, Key3:Value3...}\n", "\n", "```\n", ">>> dic = {'name': 'pey', 'phone': '0119993323', 'birth': '1118'}\n", "```\n", "\n", "**딕셔너리 dic의 정보**\n", "\n", "| key | value |\n", "| :---: | :---: |\n", "| name | pey |\n", "| phone | 0119993323 |\n", "| birth | 1118 |\n", "\n", "```\n", ">>> a = {1: 'hi'} # key로 정수값 1, value로 'hi'라는 문자열을 사용\n", ">>> a = {'a': [1, 2, 3]} # value에 리스트를 사용\n", "```\n", "\n", "### 딕셔너리 쌍 추가, 삭제하기" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1: 'a', 2: 'b'}" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 딕셔너리 쌍 추가하기\n", "\n", "a = {1: 'a'}\n", "a[2] = 'b'\n", "\n", "a" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1: 'a', 2: 'b', 'name': 'pey'}" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a['name'] = 'pey'\n", "\n", "a" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1: 'a', 2: 'b', 3: [1, 2, 3], 'name': 'pey'}" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a[3] = [1, 2, 3]\n", "\n", "a" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{2: 'b', 3: [1, 2, 3], 'name': 'pey'}" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 딕셔너리 요소 삭제하기\n", "\n", "del a[1]\n", "\n", "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 딕셔너리를 사용하는 방법\n", "\n", "#### 딕셔너리에서 Key 사용해 Value 얻기" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "10" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "grade = {'pey': 10, 'julliet': 99}\n", "\n", "grade['pey']" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "99" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "grade['julliet']" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'pey'" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dic = {'name':'pey', 'phone':'0119993323', 'birth': '1118'}\n", "\n", "dic['name']" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'0119993323'" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dic['phone']" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'1118'" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dic['birth']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 딕셔너리 만들 때 주의할 사항\n", "\n", "- 중복된 Key를 사용하지 말라.\n", "- 존재할 경우 하나가 무시된다.\n", "- key에 리스트를 사용할 수 없다." ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1: 'b'}" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = {1: 'a', 1:'b'}\n", "\n", "a" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "unhashable type: 'list'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m{\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;34m'hi'\u001b[0m\u001b[0;34m}\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: unhashable type: 'list'" ] } ], "source": [ "a = {[1, 2]: 'hi'}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "### 딕셔너리 관련 함수들\n", "\n", "#### Key 리스트 만들기(keys)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict_keys(['name', 'phone', 'birth'])" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = {'name': 'pey', 'phone': '0119993323', 'birth': '1118'}\n", "\n", "a.keys()" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "name\n", "phone\n", "birth\n" ] } ], "source": [ "# 다음과 같이 리스트처럼 사용할 수 있으나, 리스트 고유의 함수인 append, insert, pop, remove, sort 등은 사용할 수 없다.\n", "\n", "for k in a.keys():\n", " print(k)" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['name', 'phone', 'birth']" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# dict_keys 객체를 리스트로 변환\n", "\n", "list(a.keys())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Value 리스트 만들기(values)" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict_values(['pey', '0119993323', '1118'])" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.values()" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict_items([('name', 'pey'), ('phone', '0119993323'), ('birth', '1118')])" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Key, Value 쌍 얻기(items)\n", "\n", "a.items()" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{}" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Key, Value 쌍 모두 지우기(clear)\n", "\n", "a.clear()\n", "\n", "a" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'pey'" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Key 로 Value 얻기(get)\n", "\n", "a = {'name': 'pey', 'phone': '0119993323', 'birth': '1118'}\n", "\n", "a.get('name')" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'0119993323'" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.get('phone')" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'bar'" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 찾으려는 key 값이 없을 경우 디폴트 값 반환\n", "\n", "a.get('foo', 'bar')" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 해당 Key 가 딕셔너리 안에 있는지 조사하기(in)\n", "\n", "'name' in a" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'email' in a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## 02-6 집합 자료형\n", "\n", "### 집합 자료형은 어떻게 만들까?\n", "\n", "- set 키워드를 사용, 리스트나 문자열을 입력" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 2, 3}" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s1 = set([1, 2, 3])\n", "\n", "s1" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'H', 'e', 'l', 'o'}" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s2 = set(\"Hello\")\n", "\n", "s2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 집합 자료형의 특징\n", "\n", "- 중복을 허용하지 않는다. -> 중복을 제거하기 위한 필터 역할로 종종 사용한다.\n", "- 순서가 없다(unordered)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3]" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s1 = set([1, 2, 3])\n", "l1 = list(s1)\n", "l1" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l1[0]" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(1, 2, 3)" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "t1 = tuple(s1)\n", "t1" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "t1[0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 집합 자료형을 활용하는 방법\n", "\n", "#### 교집합, 합집합, 차집합 구하기" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": true }, "outputs": [], "source": [ "s1 = set([1, 2, 3, 4, 5, 6])\n", "s2 = set([4, 5, 6, 7, 8, 9])" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{4, 5, 6}" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 교집합\n", "\n", "s1 & s2" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{4, 5, 6}" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s1.intersection(s2)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 2, 3, 4, 5, 6, 7, 8, 9}" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 합집합\n", "\n", "s1 | s2" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 2, 3, 4, 5, 6, 7, 8, 9}" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s1.union(s2)" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 2, 3}" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 차집합\n", "\n", "s1 - s2" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{7, 8, 9}" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s2 - s1" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 2, 3}" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s1.difference(s2)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{7, 8, 9}" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s2.difference(s1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 집합 자료형 관련 함수들" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 2, 3, 4}" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 값 1개 추가하기(add)\n", "\n", "s1 = set([1, 2, 3])\n", "s1.add(4)\n", "\n", "s1" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 2, 3, 4, 5, 6}" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 값 여러 개 추가하기(update)\n", "\n", "s1 = set([1, 2, 3])\n", "s1.update([4, 5, 6])\n", "\n", "s1" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 3}" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 특정 값 제거하기(remove)\n", "\n", "s1 = set([1, 2, 3])\n", "s1.remove(2)\n", "\n", "s1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## 02-7 자료형의 참과 거짓\n", "\n", "- 자료형의 참과 거짓을 구분하는 기준은 다음과 같다.\n", "\n", "| 값 | 참 or 거짓 |\n", "| :---: | :---: |\n", "| \"python\" | 참 |\n", "| \"\" | 거짓 |\n", "| [1, 2, 3] | 참 |\n", "| [] | 거짓 |\n", "| () | 거짓 |\n", "| {} | 거짓 |\n", "| 1 | 참 |\n", "| 0 | 거짓 |\n", "| None | 거짓 |\n" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4\n", "3\n", "2\n", "1\n" ] } ], "source": [ "a = [1, 2, 3, 4]\n", "\n", "while a:\n", " print(a.pop())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## 02-8 자료형의 값을 저장하는 공간, 변수\n", "\n", "- 아래 예에서 a, b, c를 변수라고 한다.\n", "- = (assignment, 할당) 기호를 사용한다.\n", "- C 언어나 JAVA처럼 자료형을 같이 쓸 필요가 없다.\n", "\n", "> 변수명 = 변수에 저장할 값\n", "\n", "```\n", ">>> a = 1\n", ">>> b = \"python\"\n", ">>> c = [1, 2, 3]\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 변수란?\n", "\n", "```\n", ">>> a = 3\n", "```\n", "\n", "- 위의 코드가 실행되면 3이라는 값을 가지는 정수 자료형(객체)가 자동으로 메모리에 생성된다.\n", "- a라는 변수는 그 정수형 객체가 저장된 메모리의 위치를 가리키게 된다.\n", "- 변수 a는 3이라는 정수형 객체를 가리키는 레퍼런스(Reference)라고도 할 수 있다." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### [파이썬에서 \"3\"은 상수가 아닌 정수형 객체이다]" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 아래 코드에서는 변수 a와 b가 모두 3이라는 정수형 객체를 가리키게 된다.\n", "- 동일한 객체를 가리키고 있는지 여부를 판단하는 내장함수 is 함수로 확인한다." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = 3\n", "b = 3\n", "\n", "a is b" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### [a, b, c]는 정말 같은 객체를 가리키는 걸까?]\n", "\n", "- 입력한 자료형에 대한 참조 개수(Reference Count)를 알려주는 sys.getrefcount 함수가 있다." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "650" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import sys\n", "\n", "sys.getrefcount(3) # 파이썬 내부적으로 이미 사용되고 있다." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "731" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "var1 = 3\n", "sys.getrefcount(3)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "732" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "var2 = 3\n", "sys.getrefcount(3)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "733" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "var3 = 3\n", "sys.getrefcount(3)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "### 변수를 만드는 여러가지 방법\n", "\n", "```\n", ">>> a, b = ('python', 'life') # 튜플로 값을 대입\n", ">>> (a, b) = 'python', 'life' # 위 예문과 동일\n", ">>> [a, b] = ['python', 'life'] # 리스트로\n", ">>> a = b = 'python' # 여러 개의 변수에 같은 값을 대입\n", "```" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5\n", "3\n" ] } ], "source": [ "# 위의 방법을 이용하여 두 변수의 값 바꾸기\n", "\n", "a = 3\n", "b = 5\n", "a, b = b, a\n", "\n", "print(a)\n", "print(b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 메모리에 생성된 변수 없애기\n", "\n", "- 생성된 정수형 객체를 없애려면 그 객체를 가키는 모든 변수를 삭제해야 한다.\n", "- 즉, 그 정수형 객체에 대한 참조개수가 0 이 되어야 한다.\n", "- Garbage collection(가비지 콜렉션)이라고도 한다." ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [], "source": [ "a = 3\n", "b = 3\n", "\n", "del(a)\n", "del(b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 리스트를 변수에 넣고 복사하고자 할 때\n", "\n", "- 아래 예에서 a = b 를 실행하면 리스트가 복사되는 것이 아니라 같은 리스트를 가리키는 변수가 되는 것이다." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 4, 3]" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [1, 2, 3]\n", "b = a\n", "a[1] = 4\n", "a" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 4, 3]" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 실제 복사하여 다른 리스트를 생성하는 방법은 다음의 2가지가 있다.\n", "\n", "#### 1. [ : ] 이용" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 4, 3]" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [1, 2, 3]\n", "b = a[:]\n", "a[1] = 4\n", "\n", "a" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3]" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 2. copy 모듈 이용" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from copy import copy\n", "\n", "b = copy(a)\n", "\n", "b is a" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.4.3" } }, "nbformat": 4, "nbformat_minor": 2 }