{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Python для сбора и анализа данных\n", "\n", "*Алла Тамбовцева, НИУ ВШЭ*\n", "\n", "*Данный ноутбук частично основан на [лекции](http://nbviewer.math-hse.info/github/ischurov/pythonhse/blob/master/Lecture%202.ipynb) Щурова И.В., курс «Программирование на языке Python для сбора и анализа данных» (НИУ ВШЭ).*" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Списки и цикл `for`" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Знакомство со списками" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Создадим список значений возраста респондентов, список `age`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "age = [23, 25, 32, 48, 19] # возраст\n", "age" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "name = [\"Анна\", \"Виктор\", \"Дмитрий\", \"Алёна\", \"Павел\"] # имена" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mix = [23, 25, \"нет ответа\", 32, \"нет ответа\"] # все вместе" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "type(mix)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "len(age) # пять элементов" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "empty = []\n", "len(empty)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(age[0]) # первый элемент age\n", "print(age[1])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(age[7])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(age[-1]) # последний элемент - он же первый с конца" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "age[-2]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Изменение и добавление элементов" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "age[0] = 32 # заменили первый элемент на 32\n", "age" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "nums = [1, 5, 8, 9]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "nums.append(10) # добавили 10\n", "nums" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "nums.extend([12, 13]) # добавили 12 и 13\n", "nums" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "L = []\n", "L.append(6)\n", "L.append(8)\n", "L" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "nums.extend(6) # случай 1: один элемент не добавится" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "[1, 2, 3] + [9, 10]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Срезы (slices)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(age) " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "age[1:3] # левый конец включается, а правый нет" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(age[1:])\n", "print(age[3:])\n", "print(age[:2])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "age[:] # опускаем все индексы" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "age[2:2] # пустой срез" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Изменение списков" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "На данный момент мы достаточно хорошо познакомились со списками. Но списки не так просты, как кажется. Давайте попробуем сделать следующее: скопировать один список в другой путем присваивания." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "L1 = [1, 8, 9, 4]\n", "L2 = L1 # сохранили список L1 в L2\n", "\n", "print(L1)\n", "print(L2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "L2[3] = 5\n", "print(L2)\n", "print(L1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# дубль два\n", "L1 = [1, 8, 9, 4]\n", "L2 = L1.copy()\n", "\n", "# теперь делаем что угодно\n", "\n", "L2[3] = 100\n", "\n", "print(L1)\n", "print(L2) # все нормально" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Цикл `for`\n", "\n", "Раз есть списки, хочется научиться пробегаться по их элементам. Например, выводить на экран не весь список `age` сразу, а постепенно, каждый элемент с новой строчки. Для этого есть циклы. Рассмотрим цикл `for`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in age:\n", " print(i)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "list1 = [1, 3, 5, 9]\n", "list2 = [] # новый список\n", "\n", "for l in list1:\n", " list2.append(l * 2) # добавляем в него значения из list1, умноженные на 2\n", "print(list2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# создадим список с номерами дней\n", "\n", "days = [2, 3, 4, 5, 6, 7, 8, 9, 10]\n", "\n", "# начальное значение времени, которое питон проводит на солнце\n", "\n", "time = 1\n", "\n", "print(1, time)\n", "\n", "# теперь будем изменять значение time в цикле\n", "# и выводить на экран номер дня и время\n", "\n", "for d in days:\n", " time = time + 3\n", " print(d, time)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Функция `range()`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# пример\n", "\n", "for j in range(0, 6):\n", " print(j)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "time = 1\n", "print(1, time)\n", "\n", "for d in range(2, 11):\n", " time = time + 3\n", " print(d, time)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "range(0, 3) # не поспоришь, но бесполезно" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "list(range(0, 3)) # значения внутри range" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "list(range(5))" ] } ], "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.4" } }, "nbformat": 4, "nbformat_minor": 2 }