2015-01-26 02:43:03 +08:00
{
2015-05-14 18:55:45 +08:00
"cells": [
2015-06-19 09:07:36 +08:00
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<small><i>This notebook was prepared by [Donne Martin](http://donnemartin.com). Source and license info is on [GitHub](https://github.com/donnemartin/data-science-ipython-notebooks).</i></small>"
]
},
2015-01-26 02:43:03 +08:00
{
2015-05-14 18:55:45 +08:00
"cell_type": "markdown",
"metadata": {},
"source": [
"# Data Structure Utilities"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* slice\n",
"* range and xrange\n",
"* bisect\n",
"* sort\n",
"* sorted\n",
"* reversed\n",
"* enumerate\n",
"* zip\n",
"* list comprehensions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## slice"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Slice selects a section of list types (arrays, tuples, NumPy arrays) with its arguments [start:end]: start is included, end is not. The number of elements in the result is stop - end."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![alt text](http://www.nltk.org/images/string-slicing.png)\n",
"\n",
"Image source: http://www.nltk.org/images/string-slicing.png"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Slice 4 elements starting at index 6 and ending at index 9:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"'Pyth'"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"seq = 'Monty Python'\n",
"seq[6:10]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Omit start to default to start of the sequence:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"'Monty'"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"seq[:5]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Omit end to default to end of the sequence:"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"'Python'"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"seq[6:]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Negative indices slice relative to the end:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"'Monty'"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"seq[-12:-7]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Slice can also take a step [start:end:step].\n",
"\n",
"Get every other element:"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"'MnyPto'"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"seq[::2]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Passing -1 for the step reverses the list or tuple:"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"'nohtyP ytnoM'"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"seq[::-1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can assign elements to a slice (note the slice range does not have to equal number of elements to assign):"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[1, 1, 2, 3, 5, 'H', 'a', 'l', 'l']"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"seq = [1, 1, 2, 3, 5, 8, 13]\n",
"seq[5:] = ['H', 'a', 'l', 'l']\n",
"seq"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Compare the output of assigning into a slice (above) versus the output of assigning into an index (below):"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[1, 1, 2, 3, 5, ['H', 'a', 'l', 'l'], 13]"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"seq = [1, 1, 2, 3, 5, 8, 13]\n",
"seq[5] = ['H', 'a', 'l', 'l']\n",
"seq"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## range and xrange"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Generate a list of evenly spaced integers with range or xrange. Note: range in Python 3 returns a generator and xrange is not available.\n",
"\n",
"Generate 10 integers:"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"range(10)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Range can take start, stop, and step arguments:"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[0, 3, 6, 9, 12, 15, 18]"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"range(0, 20, 3)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It is very common to iterate through sequences by index with range:"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"2\n",
"3\n"
2015-01-27 02:00:12 +08:00
]
2015-05-14 18:55:45 +08:00
}
],
"source": [
"seq = [1, 2, 3]\n",
"for i in range(len(seq)):\n",
" val = seq[i]\n",
" print(val)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For longer ranges, xrange is recommended and is available in Python 3 as range. It returns an iterator that generates integers one by one rather than all at once and storing them in a large list."
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"50000\n"
2015-01-27 02:00:12 +08:00
]
2015-05-14 18:55:45 +08:00
}
],
"source": [
"sum = 0\n",
"for i in xrange(100000):\n",
" if i % 2 == 0:\n",
" sum += 1\n",
"print(sum)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## bisect"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The bisect module does not check whether the list is sorted, as this check would be expensive O(n). Using bisect on an unsorted list will not result in an error but could lead to incorrect results."
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import bisect"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Find the location where an element should be inserted to keep the list sorted:"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"5"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"seq = [1, 2, 2, 3, 5, 13]\n",
"bisect.bisect(seq, 8)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Insert an element into a location to keep the list sorted:"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[1, 2, 2, 3, 5, 8, 13]"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"bisect.insort(seq, 8)\n",
"seq"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## sort"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Sort in-place O(n log n)"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[1, 3, 5, 6, 7, 9]"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"seq = [1, 5, 3, 9, 7, 6]\n",
"seq.sort()\n",
"seq"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Sort by the secondary key of str length:"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"['the', 'fox', 'over', 'quick', 'brown', 'jumps']"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"seq = ['the', 'quick', 'brown', 'fox', 'jumps', 'over']\n",
"seq.sort(key=len)\n",
"seq"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## sorted"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Return a new sorted list from the elements of a sequence O(n log n):"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[1, 2, 5, 7, 8, 9]"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sorted([2, 5, 1, 8, 7, 9])"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[' ', ' ', 'a', 'a', 'b', 'b', 'f', 'o', 'o', 'r', 'z']"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sorted('foo bar baz')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It's common to get a sorted list of unique elements by combining sorted and set:"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[1, 2, 5, 7, 8, 9, (1, 2), (4, 2)]"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"seq = [2, 5, 1, 8, 7, 9, 9, 2, 5, 1, (4, 2), (1, 2), (1, 2)]\n",
"sorted(set(seq))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## reversed"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Iterate over the sequence elements in reverse order:"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[(1, 2), (1, 2), (4, 2), 1, 5, 2, 9, 9, 7, 8, 1, 5, 2]"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"list(reversed(seq))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## enumerate"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Get the index of a collection and the value:"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"(0, 'foo')\n",
"(1, 'bar')\n",
"(2, 'baz')\n"
2015-01-27 02:00:12 +08:00
]
2015-05-14 18:55:45 +08:00
}
],
"source": [
"strings = ['foo', 'bar', 'baz']\n",
"for i, string in enumerate(strings):\n",
" print(i, string)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## zip"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Pair up the elements of sequences to create a list of tuples:"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[(1, 'foo'), (2, 'bar'), (3, 'baz')]"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"seq_1 = [1, 2, 3]\n",
"seq_2 = ['foo', 'bar', 'baz']\n",
"zip(seq_1, seq_2)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Zip takes an arbitrary number of sequences. The number of elements it produces is determined by the shortest sequence:"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[(1, 'foo', True), (2, 'bar', False)]"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"seq_3 = [True, False]\n",
"zip(seq_1, seq_2, seq_3)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"It is common to use zip for simultaneously iterating over multiple sequences combined with enumerate:"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0: 1, foo\n",
"1: 2, bar\n",
"2: 3, baz\n"
2015-01-27 02:00:12 +08:00
]
2015-01-26 02:43:03 +08:00
}
],
2015-05-14 18:55:45 +08:00
"source": [
"for i, (a, b) in enumerate(zip(seq_1, seq_2)):\n",
" print('%d: %s, %s' % (i, a, b))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Zip can unzip a zipped sequence, which you can think of as converting a list of rows into a list of columns:"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"(1, 2, 3)"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"numbers = [(1, 'one'), (2, 'two'), (3, 'three')]\n",
"a, b = zip(*numbers)\n",
"a"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"('one', 'two', 'three')"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"b"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## List Comprehensions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"List comprehensions concisely form a new list by filtering the elements of a sequence and transforming the elements passing the filter. List comprehensions take the form:\n",
"```python\n",
"[expr for val in collection if condition]\n",
"```\n",
"Which is equivalent to the following for loop:\n",
"```python\n",
"result = []\n",
"for val in collection:\n",
" if condition:\n",
" result.append(expr)\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Convert to upper case all strings that start with a 'b':"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"['BAR', 'BAZ', 'B', 'BA']"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"strings = ['foo', 'bar', 'baz', 'f', 'fo', 'b', 'ba']\n",
"[x.upper() for x in strings if x[0] == 'b']"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"List comprehensions can be nested:"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"[1, 2, 3, 4, 5, 6, 7, 8, 9]"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"list_of_tuples = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]\n",
"[x for tup in list_of_tuples for x in tup]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Dict Comprehension"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A dict comprehension is similar to a list comprehension but returns a dict.\n",
"\n",
"Create a mapping of strings and their locations in the list for strings that start with a 'b':"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"{1: 'bar', 2: 'baz', 5: 'b', 6: 'ba'}"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"{index : val for index, val in enumerate(strings) if val[0] == 'b'}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Set Comprehension"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A set comprehension is similar to a list comprehension but returns a set.\n",
"\n",
"Get the unique lengths of strings that start with a 'b':"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {
"collapsed": false
},
"outputs": [
{
"data": {
"text/plain": [
"{1, 2, 3}"
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"{len(x) for x in strings if x[0] == 'b'}"
]
2015-01-26 02:43:03 +08:00
}
2015-05-14 18:55:45 +08:00
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
2015-06-19 09:07:36 +08:00
"version": "2.7.10"
2015-05-14 18:55:45 +08:00
}
},
"nbformat": 4,
"nbformat_minor": 0
}