{ "cells": [ { "cell_type": "markdown", "metadata": { "nbsphinx": "hidden" }, "source": [ "[prev: Utilisation avancée des conteneurs](container-methods.ipynb) | [home](../index.ipynb) | [next: Lire et écrire des fichiers](open-files.ipynb)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Bien boucler en Python\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "En résumé :\n", "\n", "- dict.items(), dict.values()\n", "- sorted, enumerate, zip\n", "- all, any\n", "- min, max\n", "- sum\n", "- map\n", "\n", "Lecture : [Loop like a native](http://nedbatchelder.com/text/iter/iter.html)\n", "\n", "D'autres outils encore dans le module standard `itertools`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Comment boucler sur un dict ?" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "mon_dict = {'un': 1, 'deux': 2, 'trois': 3, 'quatre': 4}" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "clef : un\n", "clef : deux\n", "clef : trois\n", "clef : quatre\n" ] } ], "source": [ "# parcourir les clefs\n", "\n", "for clef in mon_dict:\n", " print('clef :', clef)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "valeur : 1\n", "valeur : 2\n", "valeur : 3\n", "valeur : 4\n" ] } ], "source": [ "# parcourir les valeurs\n", "\n", "for valeur in mon_dict.values():\n", " print('valeur :', valeur)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "clef : un | valeur : 1\n", "clef : deux | valeur : 2\n", "clef : trois | valeur : 3\n", "clef : quatre | valeur : 4\n" ] } ], "source": [ "# parcourir les pairs clef-valeur\n", "\n", "for clef, valeur in mon_dict.items():\n", " print(f'clef : {clef:>10} | valeur : {valeur:>10}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Changer la manière d'itérer" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.0 2.0 4.0 4.0 6.0 9.0 " ] } ], "source": [ "# sorted\n", "\n", "l = [4., 6., 2., 4., 9., 1.]\n", "\n", "for i in sorted(l):\n", " print(i, end=' ')" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "l[0] = 4.00\n", "l[1] = 6.00\n", "l[2] = 2.00\n", "l[3] = 4.00\n", "l[4] = 9.00\n", "l[5] = 1.00\n" ] } ], "source": [ "# enumerate\n", "\n", "for indice, valeur in enumerate(l):\n", " print(f'l[{indice:d}] = {valeur:.2f}')" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "a = un | b = 1\n", "a = deux | b = 2\n", "a = trois | b = 3\n", "a = quatre | b = 4\n" ] } ], "source": [ "# zip\n", "\n", "def f(a, b):\n", " return f'a = {a:>8} | b = {b:>8}'\n", "\n", "list_a = ['un', 'deux', 'trois', 'quatre']\n", "list_b = [1, 2, 3, 4]\n", "\n", "# comment appliquer f sur list_a-list_b ?\n", "\n", "for (a, b) in zip(list_a, list_b):\n", " print(f(a, b))" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[('un', 1), ('deux', 2), ('trois', 3), ('quatre', 4)]" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(zip(list_a, list_b))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Parfois, il n'y a même pas besoin de faire sa boucle" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### all / any" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on built-in function all in module builtins:\n", "\n", "all(iterable, /)\n", " Return True if bool(x) is True for all values x in the iterable.\n", " \n", " If the iterable is empty, return True.\n", "\n" ] } ], "source": [ "# on pourrait avoir besoin de ceci\n", "\n", "def tous_vrai(iterable):\n", " for element in iterable:\n", " if not element:\n", " return False\n", " return True\n", "\n", "# mais cela existe déjà\n", "\n", "help(all)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on built-in function any in module builtins:\n", "\n", "any(iterable, /)\n", " Return True if bool(x) is True for any x in the iterable.\n", " \n", " If the iterable is empty, return False.\n", "\n" ] } ], "source": [ "# on pourrait avoir besoin de ceci\n", "\n", "def au_moins_un_vrai(iterable):\n", " for element in iterable:\n", " if element:\n", " return True\n", " return False\n", "\n", "# mais cela existe déjà\n", "\n", "help(any)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### max / min" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on built-in function max in module builtins:\n", "\n", "max(...)\n", " max(iterable, *[, default=obj, key=func]) -> value\n", " max(arg1, arg2, *args, *[, key=func]) -> value\n", " \n", " With a single iterable argument, return its biggest item. The\n", " default keyword-only argument specifies an object to return if\n", " the provided iterable is empty.\n", " With two or more arguments, return the largest argument.\n", "\n" ] } ], "source": [ "# on pourrait avoir besoin de ceci\n", "\n", "def max_sequence(iterable):\n", " copie = list(iterable)\n", " result = copie[0]\n", " for valeur in copie[1:]:\n", " result = max(result, valeur)\n", " return resulr\n", "\n", "# mais cela existe déjà\n", "\n", "help(max)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### sum" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on built-in function sum in module builtins:\n", "\n", "sum(iterable, /, start=0)\n", " Return the sum of a 'start' value (default: 0) plus an iterable of numbers\n", " \n", " When the iterable is empty, return the start value.\n", " This function is intended specifically for use with numeric values and may\n", " reject non-numeric types.\n", "\n" ] } ], "source": [ "# on pourrait avoir besoin de ceci\n", "\n", "def somme_sequence(iterable, start=0):\n", " result = start\n", " for valeur in iterable:\n", " result += valeur\n", " return result\n", "\n", "# mais cela existe déjà\n", "\n", "help(sum)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### map" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on class map in module builtins:\n", "\n", "class map(object)\n", " | map(func, *iterables) --> map object\n", " | \n", " | Make an iterator that computes the function using arguments from\n", " | each of the iterables. Stops when the shortest iterable is exhausted.\n", " | \n", " | Methods defined here:\n", " | \n", " | __getattribute__(self, name, /)\n", " | Return getattr(self, name).\n", " | \n", " | __iter__(self, /)\n", " | Implement iter(self).\n", " | \n", " | __next__(self, /)\n", " | Implement next(self).\n", " | \n", " | __reduce__(...)\n", " | Return state information for pickling.\n", " | \n", " | ----------------------------------------------------------------------\n", " | Static methods defined here:\n", " | \n", " | __new__(*args, **kwargs) from builtins.type\n", " | Create and return a new object. See help(type) for accurate signature.\n", "\n" ] } ], "source": [ "# on pourrait avoir besoin de ceci\n", "\n", "def applique_sur_sequence(fontions, iterable):\n", " result = []\n", " for valeur in iterable:\n", " result.append(fonction(valeur))\n", " return result\n", "\n", "# mais cela existe déjà\n", "\n", "help(map)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercices" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Creer un dict à partir d'une liste de clefs et d'une liste de valeurs.\n", "\n", "Etant donné un dict dont les valeurs sont des entiers, extraire le sous-dict composé uniquement des valeurs paires." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.10.9" } }, "nbformat": 4, "nbformat_minor": 4 }