{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "***\n", "***\n", "# 9. 리스트의 기초\n", "***\n", "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***\n", "## 1 리스트 생성 및 기본 연산\n", "***\n", "- 리스트: 시퀀스 자료형이면서 변경 가능(Mutable)\n", "- 리스트에서 지원하는 일반적인 연산\n", " - 인덱싱, 슬라이싱, 연결, 반복, 멤버쉽 테스트" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 Great\n", "[2, 'Great'] [1, 2, 'Great']\n", "\n", "range(0, 10, 2)\n", "[0, 2, 4, 6, 8]\n", "\n", "[1, 2, 'Great', 1, 2, 'Great']\n", "[1, 2, 'Great', 3, 4, 5]\n", "3\n", "\n", "True\n" ] } ], "source": [ "l = []\n", "l = [1, 2, \"Great\"]\n", "print(l[0], l[-1])\n", "print(l[1:3], l[:])\n", "print()\n", "\n", "L = range(10)\n", "print(L[::2])\n", "print(list(L)[::2])\n", "print()\n", "\n", "print(l * 2)\n", "print(l + [3, 4, 5])\n", "print(len(l))\n", "print()\n", "print(4 in L)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Mutable 특성을 지닌 리스트의 값 변경" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['spam', 'eggs', 123, 1234]\n" ] } ], "source": [ "a = ['spam', 'eggs', 100, 1234]\n", "a[2] = a[2] + 23\n", "print(a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 리스트 원소에 대한 슬라이스 치환" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 12, 123, 1234]\n", "[1, 123, 1234]\n", "[1, 2, 3, 123, 1234]\n" ] } ], "source": [ "a = ['spam', 'eggs', 123, 1234]\n", "a[0:2] = [1, 12] # 동일한 크기에 대한 슬라이스 치환\n", "print(a)\n", "\n", "a[0:2] = [1] # 서로 다른 크기에 대한 슬라이스 치환\n", "print(a)\n", "\n", "a[0:1] = [1, 2, 3] # 서로 다른 크기에 대한 슬라이스 치환\n", "print(a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 리스트 원소에 대한 슬라이스 삭제" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[123, 1234]\n" ] } ], "source": [ "a = [1, 12, 123, 1234]\n", "a[0:2] = []\n", "\n", "print(a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 리스트 원소 사이에 슬라이스 삽입" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[123, 'spam', 'ham', 1234]\n", "[123, 'spam', 'ham']\n", "[123, 'spam', 'ham', 1234, 123, 'spam', 'ham', 1234]\n" ] } ], "source": [ "a = [123, 1234]\n", "a[1:1] = ['spam', 'ham'] # 1번째 인덱스에 삽입\n", "print(a)\n", "\n", "b = [123, 1234] \n", "b[1:2] = ['spam', 'ham'] # 1번째 원소에 대한 치환\n", "print(b)\n", "\n", "a[:0] = a # 리스트 맨 앞에 자기 자신을 삽입\n", "print(a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- del을 이용한 리스트 요소 삭제" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2, 3, 4]\n", "[2]\n" ] } ], "source": [ "a = [1, 2, 3, 4]\n", "del a[0]\n", "print(a)\n", "\n", "del a[1:]\n", "print(a)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 2, 3]\n", "[0, 2]\n", "[1, 3]\n" ] } ], "source": [ "# a = range(4)\n", "a = list(range(4))\n", "print(a)\n", "print(a[::2])\n", "\n", "del a[::2]\n", "print(a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 리스트 자체에 대한 삭제\n", " - 정확히는 리스트를 가리키는 레퍼런스를 지닌 변수 a 삭제" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'a' is not defined", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\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[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m5\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mdel\u001b[0m \u001b[0ma\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mNameError\u001b[0m: name 'a' is not defined" ] } ], "source": [ "a = range(5)\n", "del a\n", "print(a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 중첩 리스트: 리스트 안에 요소로서 리스트를 지닌 리스트" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['begin', [1, 2, 3], 'end']\n", "2\n" ] } ], "source": [ "s = [1, 2, 3]\n", "t = ['begin', s, 'end']\n", "print(t)\n", "\n", "print(t[1][1])" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['begin', [1, 100, 3], 'end']\n" ] } ], "source": [ "s[1] = 100\n", "print(t)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "['a', ['x', 'y'], 'b']\n", "['x', 'y']\n", "y\n" ] } ], "source": [ "L = [1, ['a', ['x', 'y'], 'b'], 3]\n", "print(L[0])\n", "print(L[1])\n", "print(L[1][1])\n", "print(L[1][1][1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- range: 순차적인 정수 리스트 생성 가능한 시퀀스형 range 객체 만들기" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "range(0, 10)\n", "range(5, 15)\n", "range(5, 15, 2)\n" ] } ], "source": [ "print(range(10)) # 0(Included)부터 10(Excluded)까지\n", "\n", "print(range(5, 15)) # 5(Included)부터 15(Excluded)까지\n", "\n", "print(range(5, 15, 2)) # 0(Included)부터 10(Excluded)까지, Step: 2" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n", "[5, 6, 7, 8, 9, 10, 11, 12, 13, 14]\n", "[5, 7, 9, 11, 13]\n" ] } ], "source": [ "print(list(range(10))) # 0(Included)부터 10(Excluded)까지\n", "\n", "print(list(range(5, 15))) # 5(Included)부터 15(Excluded)까지\n", "\n", "print(list(range(5, 15, 2))) # 0(Included)부터 10(Excluded)까지, Step: 2" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 inch = 0.0 centi\n", "1 inch = 2.54 centi\n", "2 inch = 5.08 centi\n", "3 inch = 7.62 centi\n", "4 inch = 10.16 centi\n", "5 inch = 12.7 centi\n", "6 inch = 15.24 centi\n", "7 inch = 17.78 centi\n", "8 inch = 20.32 centi\n", "9 inch = 22.86 centi\n" ] } ], "source": [ "for el in range(10):\n", " print(el, 'inch =', el * 2.54, 'centi')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 아래 코드가 더 좋음" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 inch = 0.00 centi\n", "1 inch = 2.54 centi\n", "2 inch = 5.08 centi\n", "3 inch = 7.62 centi\n", "4 inch = 10.16 centi\n", "5 inch = 12.70 centi\n", "6 inch = 15.24 centi\n", "7 inch = 17.78 centi\n", "8 inch = 20.32 centi\n", "9 inch = 22.86 centi\n" ] } ], "source": [ "for el in range(10):\n", " print(\"%d inch = %.2f centi\" % (el, el * 2.54))" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 inch = 0.00 centi\n", "1 inch = 2.54 centi\n", "2 inch = 5.08 centi\n", "3 inch = 7.62 centi\n", "4 inch = 10.16 centi\n", "5 inch = 12.70 centi\n", "6 inch = 15.24 centi\n", "7 inch = 17.78 centi\n", "8 inch = 20.32 centi\n", "9 inch = 22.86 centi\n" ] } ], "source": [ "for el in range(10):\n", " print(\"{0} inch = {1:.2f} centi\".format(el, el * 2.54))" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 1 2 3 4 5 6\n" ] } ], "source": [ "sun, mon, tue, wed, thu, fri, sat = range(7)\n", "print(sun, mon, tue, wed, thu, fri, sat)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 리스트 안의 각 자료가 튜플일 때 for 문을 사용하여 값 추출 방법" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "name = one , num = 1\n", "name = two , num = 2\n", "name = three , num = 3\n" ] } ], "source": [ "lt = [('one', 1), ('two', 2), ('three', 3)]\n", "for t in lt:\n", " print('name =', t[0] ,', num =', t[1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 아래 코드가 더 좋음" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "name = one, num = 1\n", "name = two, num = 2\n", "name = three, num = 3\n" ] } ], "source": [ "lt = [('one', 1), ('two', 2), ('three', 3)]\n", "for t in lt:\n", " print('name = %s, num = %s' % t)" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "name = one, num = 1\n", "name = two, num = 2\n", "name = three, num = 3\n" ] } ], "source": [ "lt = [('one', 1), ('two', 2), ('three', 3)]\n", "for t in lt:\n", " print('name = {0}, num = {1}'.format(t[0], t[1]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- for 문의 헤더에서 각 튜플의 값 추출" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "one 1\n", "two 2\n", "three 3\n" ] } ], "source": [ "lt = [('one', 1), ('two', 2), ('three', 3)]\n", "for name, num in lt:\n", " print(name, num)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- 리스트 안의 각 자료가 리스트여도 for 문의 헤더에서 동일하게 값 추출 가능" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "one 1\n", "two 2\n", "three 3\n" ] } ], "source": [ "LL = [['one', 1], ['two', 2], ['three', 3]]\n", "for name, num in LL:\n", " print(name, num)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***\n", "## 2 리스트 메소드\n", "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2-1 리스트가 지원하는 메소드" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3, 5]\n", "[1, 2, 3, 4, 5]\n" ] } ], "source": [ "s = [1, 2, 3]\n", "\n", "s.append(5) # 리스트 맨 마지막에 정수 값 5 추가\n", "print(s)\n", "\n", "s.insert(3, 4) # 3 인덱스 위치에 정수 값 4 추가\n", "print(s)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "1\n", "5\n" ] } ], "source": [ "s = [1, 2, 3, 4, 5]\n", "\n", "print(s.index(3)) # 값 3의 인덱스 반환\n", "\n", "print(s.count(2)) # 값 2의 개수 반환\n", "\n", "s = [1, 2, 2, 2, 2, 2, 3, 4, 5]\n", "print(s.count(2))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- python의 소팅 알고리즘: Timsort (변형된 merge sort)\n", " - 참고: http://orchistro.tistory.com/175" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "None\n", "[100, -7, -10, 2, 1]\n", "None\n", "[-10, -7, 1, 2, 100]\n" ] } ], "source": [ "s = [1, 2, -10, -7, 100]\n", "k = s.reverse() # 자료의 순서를 뒤집기 (반환값 없음 --> 리스트 자체의 내부 원소 배열이 변경됨) \n", "print(k)\n", "print(s)\n", "\n", "k = s.sort() # 정렬 (반환값 없음 --> 리스트 자체의 내부 원소 배열이 변경됨)\n", "print(k)\n", "print(s)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[20, 30, 40, 50]\n", "[10, 30, 20, 40, 50]\n", "[10, 30, 20, 40, 50, 60, 70]\n", "[10, 30, 20, 40, 50, 60, 70, [60, 70]]\n" ] } ], "source": [ "s = [10, 20, 30, 40, 50]\n", "s.remove(10) # 자료 값 10 삭제\n", "print(s)\n", "\n", "s = [10, 20, 30, 20, 40, 50] # 자료 값이 여러개 존재하면 첫번째 것만 삭제\n", "s.remove(20)\n", "print(s)\n", "\n", "s.extend([60, 70]) # 새로운 리스트 [60, 70]를 기존 리스트 s 뒤에 병합\n", "print(s)\n", "\n", "s.append([60, 70]) # 주의: append로 새로운 리스트를 추가하면 하나의 자료 요소로서 추가\n", "print(s)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2-2 리스트를 스택(Stack)으로 사용하기\n", "- LIFO (Last Input First Output)" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[10, 20, 30, 40, 50, 60]\n", "60\n", "[10, 20, 30, 40, 50]\n" ] } ], "source": [ "s = [10, 20, 30, 40, 50]\n", "s.append(60)\n", "print(s)\n", "\n", "# If no index is specified, a.pop() removes and returns the last item in the list. \n", "print(s.pop()) \n", "\n", "print(s)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![image](../images/stack.png)" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10\n", "[20, 30, 40, 50]\n", "30\n", "[20, 40, 50]\n" ] } ], "source": [ "s = [10, 20, 30, 40, 50]\n", "print(s.pop(0)) #0 번째 인덱스 값을 꺼낸다.\n", "\n", "print(s)\n", "\n", "print(s.pop(1)) #1 번째 인덱스 값을 꺼낸다.\n", "\n", "print(s)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2-3 리스트를 큐(Queue)로 사용하기\n", "- FIFO (First Input First Output)" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10\n", "[20, 30, 40, 50, 60]\n" ] } ], "source": [ "q = [10, 20, 30, 40, 50]\n", "q.append(60)\n", "print(q.pop(0))\n", "\n", "print(q)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![image](../images/queue.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

참고 문헌: 파이썬(열혈강의)(개정판 VER.2), 이강성, FreeLec, 2005년 8월 29일

" ] } ], "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.6.8" } }, "nbformat": 4, "nbformat_minor": 1 }