{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## [Comprehension-ök](https://python-3-patterns-idioms-test.readthedocs.io/en/latest/Comprehensions.html)\n", "\n", "A comprehension egy olyan nyelvi elem a Pythonban, amely szekvenciák tömör megadását teszi lehetővé. A comprehension némileg hasonlít a matematikában alkalmazott, [tulajdonság alapján történő halmazmegadásra](https://en.wikipedia.org/wiki/Set-builder_notation) (példa: a páratlan számok halmaza megadható $\\{2k + 1\\ |\\ k \\in \\mathbb{Z}\\}$ módon)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Feltétel nélküli comprehension" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Állítsuk elő az első 10 négyzetszám listáját gyűjtőváltozó használatával!\n", "l = []\n", "for i in range(1, 11):\n", " l.append(i**2)\n", "l" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Ugyanez tömörebben, lista comprehension-nel:\n", "l = [i**2 for i in range(1, 11)]\n", "l" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 4, 9, 16, 25, 36, 49, 64, 81, 100}" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Állítsuk elő az első 10 négyzetszám halmazát gyűjtőváltozó használatával!\n", "s = set()\n", "for i in range(1, 11):\n", " s.add(i**2)\n", "s" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 4, 9, 16, 25, 36, 49, 64, 81, 100}" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Ugyanez tömörebben, halmaz comprehension-nel:\n", "s = {i**2 for i in range(1, 11)}\n", "s" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a': 97, 'e': 101, 'i': 105, 'o': 111, 'u': 117}" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Állítsunk elő egy szótárat, amely az angol kisbetűs magánhangzókhoz hozzárendeli az ASCII-kódjukat!\n", "# Használjunk gyűjtőváltozót!\n", "d = {}\n", "for ch in 'aeiou':\n", " d[ch] = ord(ch)\n", "d" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a': 97, 'e': 101, 'i': 105, 'o': 111, 'u': 117}" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Ugyanez tömörebben, szótár comprehension-nel:\n", "d = {ch: ord(ch) for ch in 'aeiou'}\n", "d" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Megjegyzés: Tuple comprehension nincs." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[(10, 'alma'), (20, 'körte'), (30, 'barack')]" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Feladat: Párok tagjainak megcserélése egy listában.\n", "pairs = [('alma', 10), ('körte', 20), ('barack', 30)]\n", "[(p[1], p[0]) for p in pairs]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Feltételes comprehension" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[4, 16, 36, 64, 100]" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Feltételes lista comprehension.\n", "[i**2 for i in range(1, 11) if i % 2 == 0]" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{4, 16, 36, 64, 100}" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Feltételes halmaz comprehension.\n", "{i**2 for i in range(1, 11) if i % 2 == 0}" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a': 97, 'e': 101, 'o': 111, 'u': 117}" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Feltételes szótár comprehension.\n", "{ch: ord(ch) for ch in 'aeiou' if ch != 'i'}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A sum, min, max függvények" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "12\n", "3.3000000000000003\n", "3.3\n", "(3+5j)\n" ] } ], "source": [ "# Számítsuk ki számok összegét a sum függvénnyel.\n", "\n", "# Az adatok egész számok egy listában.\n", "print(sum([1, 8, 3]))\n", "\n", "# Az adatok valós számok egy listában.\n", "print(sum([1.1, 2.2]))\n", "\n", "# Az adatok egész és valós számok egy tuple-ban.\n", "print(sum((1, 2.3)))\n", "\n", "# Az adatok complex számok egy halmazban.\n", "print(sum({1 + 2j, 2 + 3j}))" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "unsupported operand type(s) for +: 'int' and 'str'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "Cell \u001b[1;32mIn[12], line 2\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[38;5;66;03m# Ha az elemek nem számok, hibát kapunk!\u001b[39;00m\n\u001b[1;32m----> 2\u001b[0m \u001b[38;5;28msum\u001b[39m([\u001b[38;5;241m3\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124malma\u001b[39m\u001b[38;5;124m'\u001b[39m])\n", "\u001b[1;31mTypeError\u001b[0m: unsupported operand type(s) for +: 'int' and 'str'" ] } ], "source": [ "# Ha az elemek nem számok, hibát kapunk!\n", "sum([3, 'alma'])" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2.8\n", "5\n", "a\n", "m\n", "Lady Marian\n", "Robin Hood\n" ] } ], "source": [ "# Minimum/maximum érték (ahol az adatok összehasonlíthatók).\n", "\n", "# Az adatok számok.\n", "print(min(3, 5, 2.8))\n", "\n", "# Az adatok számok egy listában.\n", "print(max([3, 5, 2.8]))\n", "\n", "# Az adat egy db sztring, azaz karakterek egy szekvenciája.\n", "print(min('alma'))\n", "print(max('alma'))\n", "\n", "# Az adatok sztringek.\n", "print(min('Little John', 'Lady Marian', 'Robin Hood'))\n", "\n", "# Az adatok sztringek egy listában.\n", "print(max(['Little John', 'Lady Marian', 'Robin Hood']))" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'<' not supported between instances of 'str' and 'int'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "Cell \u001b[1;32mIn[14], line 2\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[38;5;66;03m# Ha az elemek nem összehasonlíthatók, hibát kapunk!\u001b[39;00m\n\u001b[1;32m----> 2\u001b[0m \u001b[38;5;28mmin\u001b[39m(\u001b[38;5;241m3\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124malma\u001b[39m\u001b[38;5;124m'\u001b[39m)\n", "\u001b[1;31mTypeError\u001b[0m: '<' not supported between instances of 'str' and 'int'" ] } ], "source": [ "# Ha az elemek nem összehasonlíthatók, hibát kapunk!\n", "min(3, 'alma')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Rendezés" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "# Lista rendezése helyben.\n", "l = [2, 11, 10, 3]\n", "l.sort()" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[2, 3, 10, 11]" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[11, 10, 3, 2]" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Rendezés csökkenő sorrendbe.\n", "l.sort(reverse=True)\n", "l" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'<' not supported between instances of 'str' and 'int'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "Cell \u001b[1;32mIn[18], line 3\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[38;5;66;03m# Fontos, hogy az elemek összehasonlíthatók legyenek!\u001b[39;00m\n\u001b[0;32m 2\u001b[0m l \u001b[38;5;241m=\u001b[39m [\u001b[38;5;241m1\u001b[39m, \u001b[38;5;241m2\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124malma\u001b[39m\u001b[38;5;124m'\u001b[39m]\n\u001b[1;32m----> 3\u001b[0m l\u001b[38;5;241m.\u001b[39msort()\n", "\u001b[1;31mTypeError\u001b[0m: '<' not supported between instances of 'str' and 'int'" ] } ], "source": [ "# Fontos, hogy az elemek összehasonlíthatók legyenek!\n", "l = [1, 2, 'alma']\n", "l.sort()" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "# Ha csak sztringeket tartalmaz a lista, akkor lehet rendezni.\n", "l = ['alma', 'szilva', 'körte']\n", "l.sort()" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['alma', 'körte', 'szilva']" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2, 11, 10, 3]\n", "[2, 3, 10, 11]\n" ] } ], "source": [ "# Kollekció rendezése listába.\n", "l1 = [2, 11, 10, 3]\n", "l2 = sorted(l1)\n", "print(l1)\n", "print(l2)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[10, 30, 35, 40]" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Tuple elemeit is rendezhetjük új listába.\n", "sorted((40, 10, 30, 35))" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[10, 30, 35, 40]" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# ... és halmaz elemeit is.\n", "sorted({40, 10, 30, 35})" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['alma', 'cseresznye', 'körte']" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Szótár esetén a sorted a kulcsokat rendezi.\n", "d = {'cseresznye': 10, 'alma': 20, 'körte': 30}\n", "sorted(d)" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a', 'a', 'i', 'l', 'm', 'v']" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Sztring esetén a sorted a karaktereket rendezi.\n", "sorted('valami')" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[('bor', 5), ('bor', 20), ('pálinka', 30), ('sör', 10)]" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Párok listájának rendezése (lexikografikusan).\n", "pairs = [('sör', 10), ('bor', 20), ('pálinka', 30), ('bor', 5)]\n", "sorted(pairs)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Megjegyzés:\n", "- A Python rendező algoritmusa a Timsort.\n", "- Időigény: O(n*log(n)), ahol n a rendezendő szekvencia hossza.\n", "- A rendező algoritmus stabil (egyenlőség esetén megőrzi az eredeti sorrendet)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Kicsomagolás ([unpacking](https://treyhunner.com/2018/03/tuple-unpacking-improves-python-code-readability/))" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [], "source": [ "# Általános eset.\n", "x, [y, z] = (10, 20, 30), ['alma', [1, 2]]" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(10, 20, 30)" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'alma'" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "y" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2]" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "z" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "ename": "ValueError", "evalue": "too many values to unpack (expected 2)", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", "Cell \u001b[1;32mIn[31], line 2\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[38;5;66;03m# Ha a bal és jobb oldal nem illeszthető egymásra, hibát kapunk.\u001b[39;00m\n\u001b[1;32m----> 2\u001b[0m x, y \u001b[38;5;241m=\u001b[39m \u001b[38;5;241m10\u001b[39m, \u001b[38;5;241m20\u001b[39m, \u001b[38;5;241m30\u001b[39m\n", "\u001b[1;31mValueError\u001b[0m: too many values to unpack (expected 2)" ] } ], "source": [ "# Ha a bal és jobb oldal nem illeszthető egymásra, hibát kapunk.\n", "x, y = 10, 20, 30" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "20\n", "30\n" ] } ], "source": [ "# Többszörös értékadás.\n", "x, y = 20, 30\n", "print(x)\n", "print(y)" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "30\n", "20\n" ] } ], "source": [ "# Csere.\n", "x = 20\n", "y = 30\n", "x, y = y, x\n", "print(x)\n", "print(y)" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "tulipán 10\n", "rózsa 20\n", "liliom 30\n" ] } ], "source": [ "# Kicsomagolás alkalmazása for ciklusnál.\n", "pairs = [('tulipán', 10), ('rózsa', 20), ('liliom', 30)]\n", "for x, y in pairs:\n", " print(x, y)" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10 100\n", "20 200\n" ] } ], "source": [ "# Kicsomagolás alkalmazása szótárnál.\n", "d = {10: 100, 20: 200}\n", "for x, y in d.items():\n", " print(x, y)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Haladó indexelés ([slicing](https://docs.python.org/3/library/functions.html#slice))\n", "\n", "- A slice jelölésmód szintaxisa [alsó határ: felső határ: lépésköz].\n", "- A kiválasztás intervalluma felülről nyitott, azaz a felső határ adja meg az első olyan indexet, amelyet már éppen nem választunk ki." ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [], "source": [ "# Példák haladó indexelésre.\n", "\n", "# 0 1 2 3 4 5 6 7\n", "####################################################\n", "data = ['alma', 'tulipán', 10, 20, 15, 25, 100, 200]" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['tulipán', 10, 20, 15, 25]" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Elemek kiválasztása az 1.-től az 5. indexig.\n", "data[1: 6: 1]" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['tulipán', 20, 25]" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Az 1-es, 3-as és 5-ös indexű elem kiválasztása.\n", "data[1: 7: 2]" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['alma', 'tulipán', 10, 20]" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Az alsó határ, a felső határ és a lépésköz is elhagyható.\n", "# Az első 4 elem kiválasztása.\n", "data[:4]" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['tulipán', 20, 25, 200]" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Minden 2. elem kiválasztása, az 1-es elemtől kezdve.\n", "data[1::2]" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['alma', 'tulipán', 10, 20, 15, 25, 100]" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Használhatunk negatív indexeket is, a mínusz 1-edik jelenti az utolsó elemet.\n", "# Az utolsó kivételével az összes elem kiválasztása.\n", "data[:-1]" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "100" ] }, "execution_count": 42, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# A negatív indexek hagyományos indexelésnél is használhatók.\n", "# Az utolsó előtti elem kiválasztása.\n", "data[-2]" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[200, 100, 25, 15, 20, 10, 'tulipán', 'alma']" ] }, "execution_count": 43, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# A lépésköz is lehet negatív.\n", "# A lista megfordítása.\n", "data[::-1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Haladó iterálási technikák" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### [enumerate](https://docs.python.org/3/library/functions.html#enumerate)" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 kék\n", "1 lila\n", "2 sárga\n", "3 zöld\n" ] } ], "source": [ "# Iterálás az elemeken és indexeken egyszerre, hagyományos megoldás.\n", "x = ['kék', 'lila', 'sárga', 'zöld']\n", "for i in range(len(x)):\n", " print(i, x[i])" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 kék\n", "1 lila\n", "2 sárga\n", "3 zöld\n" ] } ], "source": [ "# Ugyanez elegánsabban, enumerate-tel:\n", "for i, xi in enumerate(x):\n", " print(i, xi)" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "enumerate" ] }, "execution_count": 46, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Az enumerate eredménye egy iterálható objektum.\n", "type(enumerate(x))" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[(0, 'kék'), (1, 'lila'), (2, 'sárga'), (3, 'zöld')]" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Átalakítás párok listájává.\n", "list(enumerate(x))" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 kék\n", "1 lila\n", "2 sárga\n", "3 zöld\n" ] } ], "source": [ "# Az enumerate kicsomagolás nélkül is használható.\n", "for y in enumerate(x):\n", " print(y[0], y[1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### [zip](https://docs.python.org/3/library/functions.html#zip)" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "sör 10\n", "bor 20\n", "rum 30\n" ] } ], "source": [ "# Iterálás több szekvencián egyszerre, hagyományos megoldás.\n", "x = ['sör', 'bor', 'rum']\n", "y = [10, 20, 30]\n", "for i in range(len(x)):\n", " print(x[i], y[i])" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "sör 10\n", "bor 20\n", "rum 30\n" ] } ], "source": [ "# Ugyanez elegánsabban, zip-pel:\n", "for xi, yi in zip(x, y):\n", " print(xi, yi)" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "zip" ] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# A zip eredménye egy iterálható objektum.\n", "type(zip(x, y))" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[('sör', 10), ('bor', 20), ('rum', 30)]" ] }, "execution_count": 52, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Átalakítás listává.\n", "list(zip(x, y))" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "sör 10\n", "bor 20\n", "rum 30\n" ] } ], "source": [ "# A zip kicsomagolás nélkül is használható.\n", "for z in zip(x, y):\n", " print(z[0], z[1])" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "sör 10\n", "bor 20\n", "rum 30\n" ] } ], "source": [ "# Ha szekvenciák hossza nem azonos, akkor az eredmény a rövidebb hosszát veszi fel.\n", "x = ['sör', 'bor', 'rum', 'pálinka']\n", "y = [10, 20, 30]\n", "for xi, yi in zip(x, y):\n", " print(xi, yi)" ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "sör 10 True\n", "bor 20 False\n", "rum 30 True\n" ] } ], "source": [ "# A zip kettőnél több szekvenciára is alkalmazható.\n", "x = ['sör', 'bor', 'rum']\n", "y = [10, 20, 30]\n", "z = [True, False, True]\n", "for xi, yi, zi in zip(x, y, z):\n", " print(xi, yi, zi)" ] } ], "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.11.3" } }, "nbformat": 4, "nbformat_minor": 2 }