{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Списки в Python " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Индексированная последовательность значений, разделенных запятыми, заключенная в квадратные скобки. \n", "Имеют произвольную вложенность, т.е. могут включать в себя любые вложенные списки. \n", "Физически представляет собой массив указателей на его элементы. \n", "С точки зрения производительности имеют следующие особенности. \n", "1. Время доступа к элементу есть величина постоянная и не зависит от размера списка.\n", "2. Время на добавление одного элемента в конец списка есть величина постоянная. \n", "3. Время на вставку зависит от того, сколько элементов находится справа от него, т.е. чем ближе элемент к концу списка, тем быстрее идет его вставка. \n", "4. Удаление элемента происходит так же, как и в пункте 3. \n", "5. Время, необходимое на реверс списка, пропорционально его размеру — O(n). \n", "6. Время, необходимое на сортировку, зависит логарифмически от размера списка. \n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "list1 = list()\n", "list2 = []\n", "print(list1 == list2)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[]\n", "['how', 'are', 'you']\n", "['hello', 'everybody', 1, 1234, 2.778]\n" ] } ], "source": [ "lst1 = [] \n", "lst2 = ['how', 'are', 'you'] \n", "lst3 = ['hello', 'everybody', 1, 1234, 2.778]\n", "print(lst1)\n", "print(lst2)\n", "print(lst3)\n" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['everybody', 1]" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lst = ['hello', 'everybody', 1, 1234, 2.778]\n", "lst[1:3] " ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 1, 'one', 2.778]" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lst[3] = 'one' \n", "lst[0:2] = [1,2] \n", "lst " ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 'two', 'three', 2, 1, 'one', 2.778]" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lst[1:1] = ['two','three'] \n", "lst " ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0, 3, 6, 9]" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] \n", "numbers[::3] " ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['o', 'n', 'e', ' ', 't', 'w', 'o', ' ', 't', 'h', 'r', 'e', 'e']" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "st = 'one two three'\n", "lst = list(st)\n", "lst" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['one', 'two', 'three']" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "st = 'one two three'\n", "lst = list(st.split())\n", "lst" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Операции со списками" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "• копирование списка " ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3]\n", "[1, 2, 3]\n", "[1, 2, 3]\n", "L1 = [1, 2, 3]\n", "L2 = [1, 'L2[1]', 3]\n", "L3 = [1, 2, 'L3[2]']\n", "L4 = ['L4[0]', 2, 3]\n", "L1 = ['L4[0]', 2, 3]\n" ] } ], "source": [ "L1 = [1, 2, 3]\n", "print(L1)\n", "L2 = L1[:] #создание копии списка\n", "print(L2)\n", "L3 = list(L1) # создание копии списка\n", "print(L3)\n", "L2[1] = 'L2[1]'\n", "L3[2] = 'L3[2]'\n", "print('L1 = ', L1)\n", "print('L2 = ', L2)\n", "print('L3 = ', L3)\n", "L4 = L1 # указатель на тот же список\n", "L4[0] = 'L4[0]'\n", "print('L4 = ', L4)\n", "print('L1 = ', L1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "• сложение и умножение списков " ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3, 4, 5]\n", "[1, 2, 3, 1, 2, 3]\n" ] } ], "source": [ "L1 = [1, 2, 3]\n", "L2 = [4, 5]\n", "print(L1 + L2)\n", "print(L1 * 2) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "• итерация" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4 5 1 3 4 5 2 [4, 5, 1, 3, 4, 5, 2]\n", "1 2 3 4 4 5 5 [4, 5, 1, 3, 4, 5, 2]\n", "1 2 3 4 5 [4, 5, 1, 3, 4, 5, 2]\n", "2 5 4 3 1 5 4 [4, 5, 1, 3, 4, 5, 2]\n", "2 3 5 [4, 5, 1, 3, 4, 5, 2]\n" ] } ], "source": [ "L = [4, 5, 1, 3, 4, 5, 2]\n", "\n", "for x in L: \n", " print(x, end=' ')\n", "print(L)\n", "\n", "for x in sorted(L): # сортированная итерация\n", " print(x, end=' ')\n", "print(L)\n", "\n", "for x in set(L): # уникальная итерация \n", " print(x, end=' ')\n", "print(L)\n", "\n", "for x in reversed(L): #итерация в обратном порядке \n", " print(x, end=' ')\n", "print(L)\n", "\n", "L2 = [1, 4]\n", "for item in set(L).difference(L2): # исключающая итерация — вывести элементы 1-го списка, которых нет во 2-м списке \n", " print(item, end=' ')\n", "print(L)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "• конструктор списков" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 4, 9, 16, 25, 36, 49, 64, 81]" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [i * i for i in range(1, 10)] \n", "a " ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[4, 16, 36, 64]" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [i * i for i in range(1, 10) if i % 2 == 0] \n", "a " ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[(2, 'to'), (7, 'perform'), (3, 'the'), (4, 'task'), (2, 'of'), (7, 'sorting'), (3, 'the'), (5, 'words'), (2, 'in'), (1, 'a'), (6, 'string'), (2, 'by'), (5, 'their'), (6, 'length')]\n", "a by in of to the the task their words length string perform sorting\n" ] } ], "source": [ "words = 'to perform the task of sorting the words in a string by their length'.split() \n", "wordlens = [(len(word), word) for word in words] \n", "print(wordlens)\n", "wordlens.sort() \n", "print(' '.join(w for (_, w) in wordlens))\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "• распаковка списка " ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n" ] } ], "source": [ "a, b = [1, 2]\n", "print(a)\n", "print(b)" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hello\n" ] } ], "source": [ "lst = [x, s] = [12 , 'hello']\n", "print(s)" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[12, 'hello']\n", "12\n", "hello\n", "5\n", "[12, 'hello']\n", "5\n", "[10, 'hello']\n" ] } ], "source": [ "lst = [x, s] = [12 , 'hello']\n", "print(lst)\n", "print(x)\n", "print(s)\n", "x = 5\n", "print(x)\n", "print(lst)\n", "lst[0] = 10\n", "print(x)\n", "print(lst)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Встроенные функции " ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 'guitar', 'microphone', 100, 'piano', 'sintezator', 'drums']" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lst = [1, 'guitar', 'microphone', 100, 'piano'] \n", "lst2 = ['sintezator','drums']\n", "lst.extend(lst2) \n", "lst " ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3, [3, 4], 7]\n", "5\n" ] } ], "source": [ "l1 = [1, 2, 3]\n", "l2 = [3, 4]\n", "l1.append(l2)\n", "l1.append(7)\n", "print(l1)\n", "print(len(l1))" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['vocal', 1, 'guitar', 'microphone', 100, 'piano', 'sintezator', 'drums']" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lst.insert(0,'vocal') \n", "lst " ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "False\n" ] } ], "source": [ "print(100 in lst)\n", "print(10 in lst)" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lst.index('guitar') " ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "ename": "ValueError", "evalue": "'guitars' is not in list", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mlst\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mindex\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'guitars'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mValueError\u001b[0m: 'guitars' is not in list" ] } ], "source": [ "lst.index('guitars') " ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lst.count('vocal') " ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['vocal', 1, 'guitar', 'microphone', 'piano', 'sintezator', 'drums']" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lst.remove(100) \n", "lst" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['vocal', 'guitar', 'microphone', 'piano', 'sintezator', 'drums']" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "del lst[1] \n", "lst" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['drums', 'guitar', 'microphone', 'piano', 'sintezator', 'vocal']\n" ] } ], "source": [ "lst.sort() \n", "print(lst)" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['vocal', 'sintezator', 'piano', 'microphone', 'guitar', 'drums']" ] }, "execution_count": 50, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lst.reverse()\n", "lst " ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "drums\n", "['vocal', 'sintezator', 'piano', 'microphone', 'guitar']\n" ] } ], "source": [ "print(lst.pop())\n", "print(lst)" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 52, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(lst) " ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'vocal'" ] }, "execution_count": 53, "metadata": {}, "output_type": "execute_result" } ], "source": [ "max(lst) " ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'guitar'" ] }, "execution_count": 54, "metadata": {}, "output_type": "execute_result" } ], "source": [ "min(lst) " ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['vocal', 'sintezator', 'piano', 'microphone', 'guitar']" ] }, "execution_count": 55, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lst" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['vocal', 'sintezator', [1, 2, 3], 'piano', 'microphone', 'guitar']" ] }, "execution_count": 56, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lst.insert(2, [1, 2, 3])\n", "lst" ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "(1, 'tri')\n", "(2, 'dva')\n", "(3, 'raz')\n" ] } ], "source": [ "lst1 = [1, 2, 3, 4]\n", "lst2 = ['tri', 'dva', 'raz']\n", "lst = zip(lst1, lst2)\n", "print(lst)\n", "for p in lst:\n", " print(p)" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "2\n", "4\n", "6\n", "8\n" ] } ], "source": [ "lst1 = [1, 2, 3, 4]\n", "lst = map(lambda x: x*2, lst1)\n", "print(lst)\n", "for p in lst:\n", " print(p)" ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.2\n", "0.33\n", "0.43\n" ] } ], "source": [ "t1 = (1, 2, 3)\n", "t2 = (5.0, 6.0, 7.0)\n", "t = map(lambda x, y: round(x/y,2), t1, t2)\n", "for p in t:\n", " print(p)" ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "8\n", "27\n", "64\n", "125\n", "216\n", "343\n", "512\n", "729\n", "1000\n" ] } ], "source": [ "def cube(x): \n", " return x * x * x \n", "L = map(cube, range(1, 11)) \n", "for p in L:\n", " print(p)" ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "6" ] }, "execution_count": 64, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lst = [1, 2, 3]\n", "sum(lst)" ] }, { "cell_type": "code", "execution_count": 65, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(1, 2, 3)" ] }, "execution_count": 65, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tup = tuple(lst)\n", "tup" ] }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 " ] } ], "source": [ "def f(x): \n", " for y in range(2, x): \n", " if x % y == 0: \n", " return 0 \n", " return 1 \n", "\n", "L = filter(f, range(2, 100))\n", "for x in L:\n", " print(x, end = ' ')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Список как стек" ] }, { "cell_type": "code", "execution_count": 67, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4, 5, 6]" ] }, "execution_count": 67, "metadata": {}, "output_type": "execute_result" } ], "source": [ "stack = [1,2,3,4,5] \n", "stack.append(6) \n", "stack.append(7) \n", "stack.pop() \n", "stack" ] }, { "cell_type": "code", "execution_count": 68, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['two', 'three', 'four']" ] }, "execution_count": 68, "metadata": {}, "output_type": "execute_result" } ], "source": [ "queue = ['one','two','three'] \n", "queue.append('four') \n", "queue.pop(0) \n", "queue " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Ввод / вывод списка одной строкой" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 2 3 4\n", "[1, 2, 3, 4]\n", "1 2 3 4\n", "1 2 3 4\n" ] } ], "source": [ "A = list(map(int, input().split()))\n", "print(A)\n", "print(' '.join(map(str, A)))\n", "print(*A)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Пример" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [], "source": [ "l1 = list(range(1000000))\n", "l2 = [x for x in range(0, 2000000)]\n", "l3 = [x for x in range(0, 3000000)]" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "6000000\n", "Wall time: 104 ms\n" ] } ], "source": [ "%%time\n", "l1 = l1 + l2 + l3\n", "print(len(l1))" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [], "source": [ "l1 = list(range(1000000))\n", "l2 = [x for x in range(0, 2000000)]\n", "l3 = [x for x in range(0, 3000000)]" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "6000000\n", "Wall time: 69.4 ms\n" ] } ], "source": [ "%%time\n", "l1.extend(l2)\n", "l1.extend(l3)\n", "print(len(l1))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "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.7.5" } }, "nbformat": 4, "nbformat_minor": 2 }