{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "view-in-github", "colab_type": "text" }, "source": [ "\"Open" ] }, { "cell_type": "markdown", "id": "6c457f3f", "metadata": { "id": "6c457f3f" }, "source": [ "# Listas comprimidas (List comprehensions) \n", "Permite simplificar el código, habitualmente reducen varias líneas a una sola." ] }, { "cell_type": "markdown", "id": "61572b61", "metadata": { "id": "61572b61" }, "source": [ "## Listar las letras de una palabra \n", "Veamos primero un bucle ```for``` que ocupa varias líneas como se reduce luego a una sola." ] }, { "cell_type": "code", "execution_count": 1, "id": "6342804a", "metadata": { "id": "6342804a", "outputId": "b1a7dd76-16d7-4760-d4a4-ca6e44a0eb6a", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "['P', 'l', 'a', 'y', 'a']\n" ] } ], "source": [ "lista=[]\n", "for i in \"Playa\":\n", " lista.append(i)\n", "print(lista)" ] }, { "cell_type": "code", "execution_count": 2, "id": "0854b1f5", "metadata": { "id": "0854b1f5", "outputId": "73ef7a96-8788-4276-8040-5b622dc3a1d9", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "['P', 'l', 'a', 'y', 'a']" ] }, "metadata": {}, "execution_count": 2 } ], "source": [ "[letra for letra in \"Playa\"]" ] }, { "cell_type": "markdown", "id": "abe03323", "metadata": { "id": "abe03323" }, "source": [ "## Crear listas" ] }, { "cell_type": "code", "execution_count": 3, "id": "db44a5cd", "metadata": { "scrolled": true, "id": "db44a5cd", "outputId": "af4d4f25-6134-418f-a0a8-086c7a5d7cb8", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "['Berlín', 'París', 'Roma', 'Londres']\n" ] } ], "source": [ "lista=['Berlín', 'París', 'Roma', 'Londres']\n", "print([i for i in lista]) #List Comprehension: permiten crear listas de forma concisa" ] }, { "cell_type": "code", "execution_count": 4, "id": "6440e100", "metadata": { "id": "6440e100", "outputId": "0305af11-2ba2-461a-e730-4462cee0b4ae", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Berlín\n", "París\n", "Roma\n", "Londres\n" ] }, { "output_type": "execute_result", "data": { "text/plain": [ "[None, None, None, None]" ] }, "metadata": {}, "execution_count": 4 } ], "source": [ "lista=['Berlín','París','Roma','Londres']\n", "[print(i) for i in lista] #Haciéndolo iterable" ] }, { "cell_type": "markdown", "id": "4b768d79", "metadata": { "id": "4b768d79" }, "source": [ "Si ejecutamos las líneas de código previas desde una terminal llamando a un fichero **.py** no se verá el Out: \n", "[None, None, None, None]" ] }, { "cell_type": "markdown", "id": "ae040d37", "metadata": { "id": "ae040d37" }, "source": [ "## Condicional en Lista comprimida \n", "Veamos primero lo que ocupa un bucle ```for``` con un ```if``` y como se reduce luego a una sola línea." ] }, { "cell_type": "code", "execution_count": 5, "id": "d0b17d1f", "metadata": { "id": "d0b17d1f", "outputId": "7451b2ba-2ee2-4ebc-d736-c82215eda260", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]\n" ] } ], "source": [ "lista=[]\n", "for i in range(20):\n", " if not(i%2):\n", " lista.append(i)\n", "print(lista)" ] }, { "cell_type": "code", "execution_count": 6, "id": "414b45ec", "metadata": { "id": "414b45ec", "outputId": "261f5874-1368-4848-fcd7-bee961ffa4ae", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]" ] }, "metadata": {}, "execution_count": 6 } ], "source": [ "[x for x in range(20) if x%2==0]" ] }, { "cell_type": "code", "execution_count": 7, "id": "bcf0e5b3", "metadata": { "id": "bcf0e5b3", "outputId": "c4819b47-9f92-4c17-c1d7-ba45addea32d", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "['París', 'Roma']" ] }, "metadata": {}, "execution_count": 7 } ], "source": [ "ciudades = ['Berlín', 'París', 'Roma', 'Londres']\n", "[ciudad for ciudad in ciudades if 'a' in ciudad] # Obtenemos solo las ciudades que contengan una 'a'" ] }, { "cell_type": "markdown", "id": "b42fb01b", "metadata": { "id": "b42fb01b" }, "source": [ "## Condicional anidado en Lista comprimida \n", "Veamos primero lo que ocupa un bucle ```for``` con dos ```if``` y como se reduce luego a una sola línea." ] }, { "cell_type": "code", "execution_count": 8, "id": "318409ba", "metadata": { "id": "318409ba", "outputId": "de67433c-0e2d-46af-fca4-3c666e7bdc8a", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]\n" ] } ], "source": [ "lista=[]\n", "for i in range(100):\n", " if not(i % 2):\n", " if not(i % 5):\n", " lista.append(i)\n", "print(lista)" ] }, { "cell_type": "code", "execution_count": 9, "id": "d5216b24", "metadata": { "id": "d5216b24", "outputId": "c714d36e-42ed-4bff-e7bd-fbbc914ce30a", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]" ] }, "metadata": {}, "execution_count": 9 } ], "source": [ "[i for i in range(100) if i % 2 == 0 if i % 5 == 0]" ] }, { "cell_type": "markdown", "id": "4f70c895", "metadata": { "id": "4f70c895" }, "source": [ "## Utilizando ```else```" ] }, { "cell_type": "code", "execution_count": 10, "id": "e03d6798", "metadata": { "id": "e03d6798", "outputId": "a3b174ee-0f39-47f8-e9a6-344577abe5eb", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "['Impar', 'Par', 'Impar', 'Par', 'Impar', 'Par', 'Impar', 'Par', 'Impar', 'Par']\n" ] } ], "source": [ "print([\"Par\" if i % 2 == 0 else \"Impar\" for i in range(1,11)]) #Condicional con else" ] }, { "cell_type": "code", "execution_count": 11, "id": "c9b79bb2", "metadata": { "id": "c9b79bb2", "outputId": "1671795d-b955-431b-f1ae-d43362d82829", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "['Impar', (2, 'Par'), 'Impar', (4, 'Par'), 'Impar', (6, 'Par'), 'Impar', (8, 'Par'), 'Impar', (10, 'Par')]\n" ] } ], "source": [ "print([(i,\"Par\") if i % 2 == 0 else \"Impar\" for i in range(1,11)]) #Condicional con else" ] }, { "cell_type": "markdown", "id": "5430ad4a", "metadata": { "id": "5430ad4a" }, "source": [ "## Transposición de una matriz\n", "### Primero: usando bucles anidados" ] }, { "cell_type": "code", "execution_count": 12, "id": "896d7b71", "metadata": { "id": "896d7b71", "outputId": "7b7b6ba9-2dd3-4259-dce3-0c22ef9c0a2d", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "[[1, 'a'], [2, 'b'], [3, 'c'], [4, 'd']]" ] }, "metadata": {}, "execution_count": 12 } ], "source": [ "transpuesta = []\n", "matriz = [[1, 2, 3, 4], ['a', 'b', 'c', 'd']]\n", "\n", "for i in range(len(matriz[0])):\n", " transpuesta_fila= []\n", "\n", " for row in matriz:\n", " transpuesta_fila.append(row[i])\n", " transpuesta.append(transpuesta_fila)\n", "\n", "m = transpuesta\n", "m" ] }, { "cell_type": "markdown", "id": "ecea8db6", "metadata": { "id": "ecea8db6" }, "source": [ "### Segundo: usando una lista comprimida" ] }, { "cell_type": "code", "execution_count": 13, "id": "22f56f24", "metadata": { "id": "22f56f24", "outputId": "14b1c2f4-91fd-4e51-cb59-1f85e3020ff3", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "[[1, 2, 3, 4], ['a', 'b', 'c', 'd']]" ] }, "metadata": {}, "execution_count": 13 } ], "source": [ "[[row[i] for row in m] for i in range(len(m[0]))]" ] }, { "cell_type": "markdown", "id": "cfcca00f", "metadata": { "id": "cfcca00f" }, "source": [ "## Devolver funciones" ] }, { "cell_type": "markdown", "id": "fa73eb6e", "metadata": { "id": "fa73eb6e" }, "source": [ "### Capitalizar las palabras de una lista" ] }, { "cell_type": "code", "execution_count": 14, "id": "cfacf411", "metadata": { "id": "cfacf411", "outputId": "71b9701c-6a7b-489a-d4a8-a7db4792d1b1", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "['Londres', 'Paris', 'Madrid']" ] }, "metadata": {}, "execution_count": 14 } ], "source": [ "[palabra.title() for palabra in ['londres', 'paris', 'madrid']]" ] }, { "cell_type": "markdown", "id": "90a7ad08", "metadata": { "id": "90a7ad08" }, "source": [ "### Calcular los cuadrados del 0 al 10" ] }, { "cell_type": "code", "execution_count": 15, "id": "acc72db7", "metadata": { "id": "acc72db7", "outputId": "53e69e95-a30a-402c-f344-35620a401794", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]" ] }, "metadata": {}, "execution_count": 15 } ], "source": [ "[num**2 for num in range(11)]" ] }, { "cell_type": "markdown", "id": "9948ea79", "metadata": { "id": "9948ea79" }, "source": [ "### Calcular dobles y cuadrados" ] }, { "cell_type": "code", "execution_count": 16, "id": "90c9c0ac", "metadata": { "id": "90c9c0ac", "outputId": "5fd66761-8c76-4ce7-a063-63bf312cf4e6", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "[(0, 0, 0),\n", " (1, 2, 1),\n", " (2, 4, 4),\n", " (3, 6, 9),\n", " (4, 8, 16),\n", " (5, 10, 25),\n", " (6, 12, 36),\n", " (7, 14, 49),\n", " (8, 16, 64),\n", " (9, 18, 81),\n", " (10, 20, 100)]" ] }, "metadata": {}, "execution_count": 16 } ], "source": [ "[(num, num*2, num**2) for num in range(11)]" ] }, { "cell_type": "markdown", "id": "0990d4a5", "metadata": { "id": "0990d4a5" }, "source": [ "**Ejercicio** \n", "Crear un diccionario donde la clave sean los números pares del 0 al 10 y el valor sean sus cuadrados." ] }, { "cell_type": "markdown", "id": "5eb9a712", "metadata": { "id": "5eb9a712" }, "source": [ "### Listar archivos \n", "Listar los archivos del directorio img que comienzan por t y finalizan por .png" ] }, { "cell_type": "markdown", "source": [ "Primero clonamos el repositorio." ], "metadata": { "id": "Lk_AMJbu1O6Z" }, "id": "Lk_AMJbu1O6Z" }, { "cell_type": "code", "source": [ "!git clone https://github.com/financieras/pyCourse.git" ], "metadata": { "id": "9N-cSPIq1Sip", "outputId": "57dd8fcd-8d90-4f50-ec3c-ec6283f81e4c", "colab": { "base_uri": "https://localhost:8080/" } }, "id": "9N-cSPIq1Sip", "execution_count": 18, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Cloning into 'pyCourse'...\n", "remote: Enumerating objects: 5797, done.\u001b[K\n", "remote: Counting objects: 100% (391/391), done.\u001b[K\n", "remote: Compressing objects: 100% (138/138), done.\u001b[K\n", "remote: Total 5797 (delta 304), reused 310 (delta 253), pack-reused 5406\u001b[K\n", "Receiving objects: 100% (5797/5797), 4.78 MiB | 9.35 MiB/s, done.\n", "Resolving deltas: 100% (4326/4326), done.\n" ] } ] }, { "cell_type": "markdown", "source": [ "Vemos en qué directorio estamos." ], "metadata": { "id": "LNRen1H22Xe_" }, "id": "LNRen1H22Xe_" }, { "cell_type": "code", "source": [ "!pwd" ], "metadata": { "id": "iHwgyPgX13Kk", "outputId": "f8b1b990-bd24-41db-9a7c-fc1b350c5c80", "colab": { "base_uri": "https://localhost:8080/" } }, "id": "iHwgyPgX13Kk", "execution_count": 23, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "/content\n" ] } ] }, { "cell_type": "code", "execution_count": 24, "id": "9390e26e", "metadata": { "id": "9390e26e", "outputId": "d7885de1-feab-47ba-baaa-839c61ca23b5", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "['tablanotas.png', 'taza.png', 'tablaverdad.png']\n" ] } ], "source": [ "import os\n", "\n", "ficheros = [f for f in os.listdir('./pyCourse/jupyter/img') if f.endswith('.png') and f.startswith('t')]\n", "\n", "print(ficheros)" ] }, { "cell_type": "markdown", "id": "037bb506", "metadata": { "id": "037bb506" }, "source": [ "## Doble bucle ```for```" ] }, { "cell_type": "code", "execution_count": 25, "id": "006cfc52", "metadata": { "id": "006cfc52", "outputId": "55aa1e24-8cd6-4549-db68-3404f58279a4", "colab": { "base_uri": "https://localhost:8080/" } }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "['Sota de Oros', 'Sota de Copas', 'Sota de Espadas', 'Sota de Bastos', 'Caballo de Oros', 'Caballo de Copas', 'Caballo de Espadas', 'Caballo de Bastos', 'Rey de Oros', 'Rey de Copas', 'Rey de Espadas', 'Rey de Bastos']\n" ] } ], "source": [ "cartas = ['sota', 'caballo', 'rey']\n", "palos = ['oros', 'copas', 'espadas', 'bastos']\n", "\n", "frases = ['{} de {}'.format(carta.title(), palo.title()) for carta in cartas for palo in palos]\n", "\n", "print(frases)" ] } ], "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.8.11" }, "colab": { "name": "0410_list_comprehension.ipynb", "provenance": [], "include_colab_link": true } }, "nbformat": 4, "nbformat_minor": 5 }