From 4d3960d83f85f0ce4a1a9c354d72f9ab16f9e6a3 Mon Sep 17 00:00:00 2001 From: Donne Martin Date: Tue, 27 Jan 2015 13:15:47 -0500 Subject: [PATCH] Added itertools snippet. --- core/functions.ipynb | 55 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 53 insertions(+), 2 deletions(-) diff --git a/core/functions.ipynb b/core/functions.ipynb index 82d9e80..51518e1 100644 --- a/core/functions.ipynb +++ b/core/functions.ipynb @@ -1,7 +1,7 @@ { "metadata": { "name": "", - "signature": "sha256:d9c538ef6dad540e5963356ed91d625e86a9a447c42edc8d3fe3a76031768782" + "signature": "sha256:7302df53c9f267690231320dc5731929b2c6969b01ff3cfc482e4708b66f2162" }, "nbformat": 3, "nbformat_minor": 0, @@ -25,7 +25,8 @@ "* \\*args, \\*\\*kwargs\n", "* Currying\n", "* Generators\n", - "* Generator Expressions" + "* Generator Expressions\n", + "* itertools" ] }, { @@ -512,6 +513,56 @@ } ], "prompt_number": 11 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## itertools\n", + "\n", + "The library itertools has a collection of generators useful for data analysis.\n", + "\n", + "Function groupby takes a sequence and a key function, grouping consecutive elements in the sequence by the input function's return value (the key). groupby returns the function's return value (the key) and a generator." + ] + }, + { + "cell_type": "code", + "collapsed": false, + "input": [ + "import itertools\n", + "first_letter = lambda x: x[0]\n", + "strings = ['foo', 'bar', 'baz']\n", + "for letter, gen_names in itertools.groupby(strings, first_letter):\n", + " print letter, list(gen_names)" + ], + "language": "python", + "metadata": {}, + "outputs": [ + { + "output_type": "stream", + "stream": "stdout", + "text": [ + "f ['foo']\n", + "b ['bar', 'baz']\n" + ] + } + ], + "prompt_number": 18 + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "itertools contains many other useful functions:\n", + "\n", + "| Function | Description|\n", + "| ------------- |-------------|\n", + "| imap | Generator version of map |\n", + "| ifilter | Generator version of filter |\n", + "| combinations | Generates a sequence of all possible k-tuples of elements in the iterable, ignoring order |\n", + "| permutations | Generates a sequence of all possible k-tuples of elements in the iterable, respecting order |\n", + "| groupby | Generates (key, sub-iterator) for each unique key |" + ] } ], "metadata": {}