Skip to content

Instantly share code, notes, and snippets.

@suzaninfi
Last active October 19, 2021 09:54
Show Gist options
  • Select an option

  • Save suzaninfi/ee53164a86ace2165573ae1f473dc251 to your computer and use it in GitHub Desktop.

Select an option

Save suzaninfi/ee53164a86ace2165573ae1f473dc251 to your computer and use it in GitHub Desktop.
Python kennisdeling List Comprehensions
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"id": "004e7e88-7397-4117-94d5-cf84ed51eac7",
"metadata": {},
"source": [
"# Python kennisdeling\n",
"\n",
"## Python\n",
"\n",
"- Fijne script taal\n",
"- Object oriented\n",
"- Geen (strikte) types, maar kan voor linters/IDEs\n",
"- Leesbare taal: `if value is not None and value < 10`\n",
"- Geen curly brackets voor code blocks en geen puntkomma's (😱) :\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "abfd7a8e-1e3c-42ea-80a9-f80f9bb856c6",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"smol\n",
"4\n",
"smol\n",
"11\n",
"big\n"
]
}
],
"source": [
"numbers = [1, 4, 11]\n",
"for n in numbers:\n",
" print(n)\n",
" if n < 5:\n",
" print(\"smol\")\n",
" else:\n",
" print(\"big\")"
]
},
{
"cell_type": "markdown",
"id": "dcfb422a-4da2-456f-8841-23caa55b867e",
"metadata": {},
"source": [
"* Conventie namen functies en variabelen in `snake_case`\n",
"* Goed voor data manipulatie (`pandas` dataframes, `sckikit-learn`)\n",
"* Deze leuke notebooks (`jupyter`)!"
]
},
{
"cell_type": "markdown",
"id": "4168b575-c070-46c5-b7db-5e6888660dfd",
"metadata": {},
"source": [
"# List Comprehensions"
]
},
{
"cell_type": "markdown",
"id": "99883063-7de1-4d5f-815b-e40cbb4aac0e",
"metadata": {
"tags": []
},
"source": [
"## Verzamelingen\n",
"\n",
"Verzamelingnotatie uit de wiskunde:\n",
"\n",
"$\\{x^2 \\mid x \\in \\{1,2,3,4,5\\},\\ x\\bmod2 = 0\\}$\n",
"\n",
"Verzameling kwadraten van even getallen tussen 1 en 5.\n",
"\n",
"Resulteert in de verzameling $\\{4, 16\\}$\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "d2f48f83-15cb-4137-8cda-987e4ed5e4d5",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[4, 16]"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"[x*x for x in [1,2,3,4,5] if x % 2 == 0]"
]
},
{
"cell_type": "markdown",
"id": "fc0cc9d8-b8b8-4ccc-9eaf-83c2f31b59f3",
"metadata": {},
"source": [
"## Algemene vorm\n",
"\n",
"```python\n",
"[expression_with_item for item in iterable if condition]\n",
"```\n",
"\n",
"### Map/Filter\n",
"Met *list comprehensions* kun je nabootsen wat je normal met `map` en `filter` zou doen.\n",
"\n",
"Lijst met namen:"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "d81642ea-406a-4415-87ac-b8f6cc868c04",
"metadata": {},
"outputs": [],
"source": [
"NAMES = ['Wario', 'Daisy', 'Waluigi']"
]
},
{
"cell_type": "markdown",
"id": "2061507e-7e58-47e5-bb39-d5d6db56fcb7",
"metadata": {},
"source": [
"#### Map\n",
"Zet elke naam in lowercase.\n",
"In javascript:\n",
"```js\n",
"NAMES.map(name => name.toLower())\n",
"```\n",
"Met list comprehension:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "f6b1fbb9-70a7-4548-ae8c-a0b2d64dbd25",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['wario', 'daisy', 'waluigi']"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"[name.lower() for name in NAMES]"
]
},
{
"cell_type": "markdown",
"id": "ad7318e7-7645-46bf-95fd-d9eb4fa92399",
"metadata": {
"tags": []
},
"source": [
"#### Filter\n",
"Pak alle namen die beginnen met een `W`. In javascript:\n",
"```js\n",
"NAMES.filter(name => name.startsWith('W'));\n",
"```\n",
"Met list comprehension:"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "fc13c588-0364-410e-b2ba-2fa309f6d887",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['Wario', 'Waluigi']"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"[name for name in NAMES if name.startswith('W')]"
]
},
{
"cell_type": "markdown",
"id": "461558f9-ac89-48d5-9375-131bdeec4c33",
"metadata": {
"tags": []
},
"source": [
"#### Map + Filter\n",
"\n",
"Pak namen die beginnen met een `W` én maak ze lowercase. In javascript:\n",
"```js\n",
"NAMES.filter(name => name.startsWith('W')).map(name => name.toLower());\n",
"```\n",
"Met list comprehension:\n"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "a59608e7-287c-4e25-8b23-56062a179919",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['wario', 'waluigi']"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"[name.lower() for name in NAMES if name.startswith('W')]"
]
},
{
"cell_type": "markdown",
"id": "f357c838-48e2-49be-8084-74797d4161f1",
"metadata": {
"tags": []
},
"source": [
"## Voorbeelden"
]
},
{
"cell_type": "markdown",
"id": "3b285819-de9c-4f28-8e3d-e518ce236070",
"metadata": {
"tags": []
},
"source": [
"### FizzBuzz in een lijst\n",
"De eerste 40 getallen:"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "fffab314-ccf8-4ef9-80e3-bd0c5bd1f031",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['fizzbuzz',\n",
" 1,\n",
" 2,\n",
" 'fizz',\n",
" 4,\n",
" 'buzz',\n",
" 'fizz',\n",
" 7,\n",
" 8,\n",
" 'fizz',\n",
" 'buzz',\n",
" 11,\n",
" 'fizz',\n",
" 13,\n",
" 14,\n",
" 'fizzbuzz',\n",
" 16,\n",
" 17,\n",
" 'fizz',\n",
" 19,\n",
" 'buzz',\n",
" 'fizz',\n",
" 22,\n",
" 23,\n",
" 'fizz',\n",
" 'buzz',\n",
" 26,\n",
" 'fizz',\n",
" 28,\n",
" 29,\n",
" 'fizzbuzz',\n",
" 31,\n",
" 32,\n",
" 'fizz',\n",
" 34,\n",
" 'buzz',\n",
" 'fizz',\n",
" 37,\n",
" 38,\n",
" 'fizz']"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"['fizzbuzz' if x % 3 == 0 and x % 5 == 0 else 'fizz' if x % 3 == 0 else 'buzz' if x % 5 == 0 else x for x in range(40)]"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "eeff3993-fd04-4045-b7f0-a6fa3e585cc7",
"metadata": {},
"outputs": [],
"source": [
"def toFizzBuzz(i):\n",
" if i % 3 == 0 and i % 5 == 0:\n",
" return \"fizzbuzz\"\n",
" if i % 3 == 0:\n",
" return \"fizz\"\n",
" if i % 5 == 0:\n",
" return \"buzz\"\n",
" return i\n",
" \n",
"fizzbuzz = [toFizzBuzz(x) for x in range(40)]"
]
},
{
"cell_type": "markdown",
"id": "5f0da432-ec01-44b4-91eb-e7c199dc8361",
"metadata": {
"tags": []
},
"source": [
"### Pythagorese drietallen\n",
"\n",
"Een Pythagorees drietal bestaat uit drie positieve integers $a$, $b$, en $c$, zodat $a^2$ + $b^2$ = $c^2$."
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "70891067-a7f5-4b9c-9790-c76bae77d185",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[(3, 4, 5),\n",
" (4, 3, 5),\n",
" (5, 12, 13),\n",
" (6, 8, 10),\n",
" (7, 24, 25),\n",
" (8, 6, 10),\n",
" (8, 15, 17),\n",
" (9, 12, 15),\n",
" (10, 24, 26),\n",
" (12, 5, 13),\n",
" (12, 9, 15),\n",
" (12, 16, 20),\n",
" (15, 8, 17),\n",
" (15, 20, 25),\n",
" (16, 12, 20),\n",
" (16, 30, 34),\n",
" (18, 24, 30),\n",
" (20, 15, 25),\n",
" (20, 21, 29),\n",
" (21, 20, 29),\n",
" (21, 28, 35),\n",
" (24, 7, 25),\n",
" (24, 10, 26),\n",
" (24, 18, 30),\n",
" (28, 21, 35)]"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"[(a,b,c) for a in range(1,30) for b in range(1,35) for c in range(1,40) if a**2 + b**2 == c**2]"
]
},
{
"cell_type": "markdown",
"id": "1cfbe4cd-ccb8-43b3-8f3d-2d00d2ec9525",
"metadata": {
"tags": []
},
"source": [
"\n",
"### Dictionary\n",
"Met **List comprehensions** maak je lijsten, maar zonder de lijst eromheen heb je een **generator expression**.\n",
"\n",
"Die kun je gebruiken om andere dingen dan lijsten te maken! Bijvoorbeeld dictionaries:"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "ecf7055f-04a5-4260-80c3-20ccf7b51b31",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'Wario': 1, 'Daisy': 1, 'Waluigi': 2, 'Rosalina': 1, 'Bowser': 0}"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"NAMES = ['Wario', 'Daisy', 'Waluigi', 'Rosalina', 'Toad', 'Bowser']\n",
"i_count_dict = {name : name.count('i') for name in NAMES if len(name) > 4}\n",
"\n",
"i_count_dict\n"
]
},
{
"cell_type": "markdown",
"id": "88f833bb-2897-46f6-a4c6-21a20cb68365",
"metadata": {},
"source": [
"### Geen lijst nodig"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "e31ad473-1df1-4345-a82c-3ed22b6141e1",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'0, 1, 2, 3, 4, 5, 6, 7, 8, 9'"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"\", \".join(str(n) for n in range(10))"
]
},
{
"cell_type": "markdown",
"id": "27f76d7e-37fc-4dde-a952-b65aaeb3b5c3",
"metadata": {},
"source": [
"#### Efficiënt"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "f69e55f5-85f7-4e0c-ad7c-d6705228dfc7",
"metadata": {},
"outputs": [],
"source": [
"from time import time"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "51fc8693-7ecd-46ce-a48c-4956ad5d96a4",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2.6971793174743652"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"now = time()\n",
"numbers = 20000000 * [1]\n",
"for i in range(20000000):\n",
" numbers[i] = i*i\n",
"sum(numbers)\n",
"time() - now"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "aa6ec2d7-2c91-48b3-a412-d0ced341f773",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2.3796908855438232"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"now = time()\n",
"sum([i * i for i in range(20000000)])\n",
"time() - now"
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "bc147e94-0aa9-4572-8e3e-cfc4983335d7",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1.3587019443511963"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"now = time()\n",
"sum(i * i for i in range(20000000))\n",
"time() - now"
]
},
{
"cell_type": "markdown",
"id": "2224ffff-455a-4817-ad25-249d23d07d69",
"metadata": {},
"source": [
"### Dubbele loop"
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "70c691b0-4ed0-425e-a74a-61840bf3762a",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['ITS', 'A', 'ME', 'MARIO!', 'THANK', 'YOU', 'FOR', 'PLAYING', 'MY', 'GAME']"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sentences = [\n",
" ['Its', 'a', 'me', 'Mario!'],\n",
" ['Thank', 'you', 'for', 'playing', 'my', 'game']\n",
"]\n",
"list_of_words = []\n",
"for sentence in sentences:\n",
" for word in sentence:\n",
" list_of_words.append(word.upper())\n",
" \n",
"list_of_words"
]
},
{
"cell_type": "code",
"execution_count": 17,
"id": "a2ea5a75-b033-4aff-9a88-54af580587ca",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['ITS', 'A', 'ME', 'MARIO!', 'THANK', 'YOU', 'FOR', 'PLAYING', 'MY', 'GAME']"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"[word.upper() for sentence in sentences for word in sentence]"
]
},
{
"cell_type": "markdown",
"id": "dbfe2225-16e6-4bec-a057-1a2a58c71f66",
"metadata": {},
"source": [
"## Conclusie\n",
"Waarom list / generator comprehensions?\n",
"\n",
"- Elegante one-liners\n",
"- Efficiënter dan for-loops (maar gebruik numpy en array computations als efficiëntie echt belangrijk zijn)\n",
"- Leesbaar, áls je ze gebruikt wanneer ze gepast zijn (liever niet voor double loops)\n",
"- Direct duidelijk dat je een lijst / dictionary / ... aan het maken bent zonder loop te hoeven lezen\n"
]
}
],
"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.9.6"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment