{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Структуры данных\n", "* позволяют хранить и обрабатывать множество однотипных данных\n", "* имеют встроенные методы для добавления, поиска, изменения и удаления данных\n", "* так как в Python используется *динамическая типизация*, типы данных определяются автоматически во время исполнения, и заранее объявлять их не нужно\n", "\n", "### Неизменяемые структуры:\n", "* строки\n", "* кортежи\n", "* числа\n", "* фиксированные множества (frozenset)\n", "\n", "### Изменяемые структуры:\n", "* списки\n", "* словари\n", "* множества (set)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Строки в Python" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'str' object does not support item assignment", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;31m# неизменяемые\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[0mword\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;34m'magistratura'\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[0mword\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;34m'M'\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mTypeError\u001b[0m: 'str' object does not support item assignment" ] } ], "source": [ "# неизменяемые\n", "word = 'magistratura' \n", "word[0] = 'M'" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'mag!stratura'" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "word = 'magistratura'\n", "word = word[:3] + '!' + word[4:] \n", "word\n" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'mAgistrAturA'" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "word = 'magistratura'\n", "word = word.replace('a','A')\n", "word" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'u'" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "word = 'magistratura'\n", "word[-3]" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "123\n", "7'8''9\n", "45\"6\"7\n", "7'8''945\"6\"7\n" ] } ], "source": [ "s1 = '123'\n", "s2 = \"7'8''9\"\n", "s3 = '45\"6\"7'\n", "print(s1)\n", "print(s2)\n", "print(s3)\n", "print(s2+s3)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'this is the first line and this is the second line'" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s = 'this is the first line \\\n", "and this is the second line'\n", "s" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'\\nOne\\n Two \\nThree \\n'" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s = '''\n", "One\n", " Two \n", "Three \n", "'''\n", "s" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'a\\nb\\tc'" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s ='a\\nb\\tc' \n", "s" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "7ĵf\n", "3\n" ] } ], "source": [ "s = '\\067\\465\\x66' \n", "print(s)\n", "print(len(s))" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "123\n", "3\n" ] } ], "source": [ "s = str(123)\n", "print(s)\n", "print(len(s))" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "123\n" ] } ], "source": [ "s = int('123')\n", "print(type(s))\n", "print(s)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "123.45" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s = float('123.45')\n", "s" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "57\n", "b\n" ] } ], "source": [ "print(ord('9'))\n", "print(chr(98))" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "а\n", "ш\n" ] } ], "source": [ "s = 'чебурашка'\n", "print(min(s))\n", "print(max(s))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Срезы\n", "\n", "механизм гибкого управления строкой на основе индексации" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "s\n", "mag\n", "mag\n", "gis\n", "tura\n", "tu\n" ] } ], "source": [ "word = 'magistratura' \n", "print(word[4])\n", "print(word[0:3])\n", "print(word[:3])\n", "print(word[2:5]) \n", "print(word[8:])\n", "print(word[8:-2])" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0123456789\n", "3579\n", "9876543210\n" ] } ], "source": [ "s = '0123456789' \n", "print(s[::])\n", "print(s[3::2]) \n", "print(s[::-1])" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Kirov city'" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s = 'Kirov' + ' city'\n", "s" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'123123123'" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "t = '123' * 3\n", "t" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Форматирование\n", "\n", "Таблица типов форматирования для строк\n", "\n", "* s, r Строковый \n", "* c Посимвольный \n", "* d, u Десятичный \n", "* i Целый \n", "* o Восьмеричный \n", "* x / X Шестнадцатеричный, нижний / верхний регистр\n", "* e / E Floating-point exponent\n", "* f / F Floating-point decimal \n", "* g Floating-point e или f \n", "* C Floating-point E или F \n", "* % Символьный % " ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello world\n", "one two three\n", "one 2 3.600000\n" ] } ], "source": [ "s = 'Hello %s' % 'world' \n", "print(s) \n", "s = 'one %s %s' % ('two','three') \n", "print(s) \n", "s = 'one %d %f' % (2 , 3.6) \n", "print(s)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 41.33333\n" ] } ], "source": [ "x = 124/3 \n", "print('%10.5f' % x) " ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'0003.1415926536'" ] }, "execution_count": 42, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from math import pi \n", "'%015.10f' % pi " ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'1 2 3 4 5'" ] }, "execution_count": 43, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from string import Template \n", "s = Template('1 $two 3 4 $five')\n", "d={} \n", "d['two']=2\n", "d['five']=5\n", "s.substitute(d)" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Out {a} and out {b}\n", "Out 3 and out 2\n" ] } ], "source": [ "a = 1\n", "b = 2\n", "print(\"Out {a} and out {b}\")\n", "print(f\"Out {a+2} and out {b}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Методы\n", "\n", "* S.capitalize() \n", "* S.center(width [, fill]) \n", "* S.count(sub [, start [, end]]) \n", "* S.encode([encoding [,errors]]) \n", "* S.endswith(suffix [, start [, end]]) \n", "* S.expandtabs([tabsize]) \n", "* S.find(sub [, start [, end]]) \n", "* S.format(fmtstr, *args, **kwargs) \n", "* S.index(sub [, start [, end]]) \n", "* S.isspace() \n", "* S.istitle() \n", "* S.isupper() \n", "* S.join(iterable) \n", "* S.ljust(width [, fill]) \n", "* S.lower() \n", "* S.lstrip([chars]) \n", "* S.maketrans(x[, y[, z]]) \n", "* S.partition(sep) \n", "* S.replace(old, new [, count])\n", "* S.rfind(sub [,start [,end]]) \n", "* S.rindex(sub [, start [, end]]) \n", "* S.rjust(width [, fill]) \n", "* S.rpartition(sep) \n", "* S.rsplit([sep[, maxsplit]]) \n", "* S.rstrip([chars]) \n", "* S.split([sep [,maxsplit]]) \n", "* S.splitlines([keepends]) \n", "* S.startswith(prefix [, start [, end]]) \n", "* S.strip([chars]) \n", "* S.swapcase() \n", "* S.title() \n", "* S.translate(map) \n", "* S.upper() \n", "* S.zfill(width)" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "9\n", "1\n", "-1\n" ] } ], "source": [ "s = 'Abrakadabra' \n", "print(s.find('ra'))\n", "print(s.rfind('ra'))\n", "print(s.find('bra')) \n", "print(s.find('bred'))" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "6\n", "1\n", "8\n" ] }, { "ename": "ValueError", "evalue": "substring not found", "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[0;32m 3\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ms\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mindex\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'bra'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ms\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mrindex\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'bra'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 5\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ms\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mindex\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'bred'\u001b[0m\u001b[1;33m)\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: substring not found" ] } ], "source": [ "s = 'Abrakadabra' \n", "print(s.index('da'))\n", "print(s.index('bra'))\n", "print(s.rindex('bra')) \n", "print(s.index('bred')) # error" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "one***two***three\n", "['one', 'two', 'three']\n", "one two three\n" ] } ], "source": [ "seq = ['one','two','three'] \n", "sep = '***' \n", "print(sep.join(seq))\n", "print(seq)\n", "print(*seq)" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['', 'usr', 'local', '', '', 'bin']\n" ] } ], "source": [ "s = '/usr/local///bin' \n", "print(s.split('/') )" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, Alexandra! Glad to see you, Alexandra!\n", "Hello, Alexandra! Glad to see you, Masha!\n" ] } ], "source": [ "s = 'Hello, Masha! Glad to see you, Masha!' \n", "print(s.replace('Masha','Alexandra'))\n", "print(s.replace('Masha','Alexandra', 1))" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1212121\n" ] } ], "source": [ "s = '12121'\n", "print(s.replace('121','Alexandra'))" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' Zoom−Zoom '" ] }, "execution_count": 52, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s = 'Zoom−Zoom'\n", "s.center(15)" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Zoom−Zoom++++++\n", " Zoom−Zoom\n" ] } ], "source": [ "s = 'Zoom−Zoom'\n", "print(s.ljust(15,'+'))\n", "print(s.rjust(15))" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s = '1235'\n", "s.isdigit()" ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "1\n", "0\n", "1\n" ] } ], "source": [ "s = 'abrakadabra'\n", "print(s.count('ab'))\n", "print(s.count('ab',1))\n", "print(s.count('ab', 1, -3))\n", "#print(s[1:-3])\n", "s= '12121'\n", "print(s.count('121'))" ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "('H', 'e', 'llo everybody')\n", "('Hello ev', 'e', 'rybody')\n" ] } ], "source": [ "s = 'Hello everybody'\n", "print(s.partition('e'))\n", "print(s.rpartition('e'))\n" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "!breKeKeKeKs!\n", "!breKeKeKeKs !\n", "! breKeKeKeKs!\n", "! breKeKeKeKs !\n", "! breKeKeKeKs !\n", "! breKeKeKeKs !\n" ] } ], "source": [ "s = ' breKeKeKeKs '\n", "print('!' + s.strip() + '!')\n", "print('!' + s.lstrip() + '!')\n", "print('!' + s.rstrip() + '!')\n", "\n", "print('!', s.strip(), '!')#,sep=' ', end='\\n')\n", "print('!', s.lstrip(), '!')\n", "print('!', s.rstrip(), '!')" ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Everything is abrakadabra\n", "Everything Is Abrakadabra\n" ] } ], "source": [ "s = 'everything is abrakadabra'\n", "print(s.capitalize())\n", "print(s.title())" ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'000000000123'" ] }, "execution_count": 62, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s = '123'\n", "s.zfill(12)" ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "zOOM−zOOM\n", "ZOOM−ZOOM\n", "zoom−zoom\n", "Zoom−Zoom\n" ] } ], "source": [ "s = 'Zoom−Zoom'\n", "print(s.swapcase())\n", "print(s.upper())\n", "print(s.lower())\n", "print(s)" ] }, { "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 }