{ "cells": [ { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/html": [ "\n", " \n", " " ], "text/plain": [ "" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from IPython.display import YouTubeVideo\n", "YouTubeVideo(\"M_eYSuPKP3Y\",width=\"640\",height=\"390\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "UC Berkeley Python Bootcamp (c) J. Bloom All Rights Reserved" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## There are four main types of collections of data (\"Sequence objects\") ##\n", "\n", "\t•\tLists: a mutable array of data\n", "\t•\tTuples: ordered, immutable list\n", "\t•\tSets: unordered collection of unique elements\n", "\t•\tDictionaries: keyword/value lookup\n", "\n", "The value in each element can be whatever (type) you want.\n", "> string is actually a sequence object" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Tuple ###\n", "denoted with parentheses" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "t = (12,-1)\n", "print(type(t))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "print(isinstance(t,tuple))\n", "print(len(t))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "t = (12,\"monty\",True,-1.23e6)\n", "print(t[1])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "print(t[-1])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "t[-2:] # get the last two elements, return as a tuple" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "x = (True) ; print(type(x))\n", "x = (True,) ; print(type(x))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "type(()), len(())" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "type((,))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "single-element tuples look like `(element,)`" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "cannot change a tuple\n", "but you can create new one with concatenation" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "t[2] = False" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "type((1,\"spam\",\"eggs\", None))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "t[0:2], False, t[3:]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "## the above it \n", "## not what we wanted... need to concatenate\n", "t[0:2] + False + t[3:]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "y = t[0:2] + (False,) + t[3:] ; print(y)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "t*2" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ " " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### List ###\n", "#### denoted with a brackets ####" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "v = [1,2,3] ; print(len(v), type(v))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "v[0:2]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "v = [\"eggs\",\"spam\",-1,(\"monty\",\"python\"),[-1.2,-3.5]]\n", "len(v)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "v[0] =\"green egg\"\n", "v[1] += \",love it.\"\n", "v[-1]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "v[-1][1]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "v[-1][1] = None ; print(v)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "v = v[2:] ; print(v)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# let's make a proto-array out of nested lists\n", "vv = [ [1,2], [3,4] ]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "print(len(vv))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "determinant = vv[0][0]*vv[1][1] - vv[0][1]*vv[1][0]\n", "print(determinant)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "the main point here: lists are **changeable** (\"mutable\")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### lists can be extended & appended ###" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "v = [1,2,3]\n", "v.append(4) \n", "print(v)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "> Lists can be considered objects.\n", "**Objects** are like animals: they know how to do stuff (like eat and sleep), they know how to interact with others (like make children), and they have characteristics (like height, weight).\n", "\n", "> \"Knowing how to do stuff\" with itself is called a method. In this case \"append\" is a method which, when invoked, is an action that changes the characteristics (the data vector of the list itself)." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### List ###\n", "#### lists can be extended, appended, and popped ####" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "v = [1,2,3]\n", "v.append(4)\n", "v.append([-5]) ; print(v)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "v = v[:4]\n", "w = ['elderberries', 'eggs']\n", "v + w" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "v.extend(w) ; print(v)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "v.pop()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "print(v)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "v.pop(0) ; print(v) ## pop the first element" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "v.append(0)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "v = [\"hello\"] + v" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(v)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ " * `.append()`: adds a new element\n", " * `.extend()`: concatenates a list/element\n", " * `.pop()`: remove an element" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### lists can be searched, sorted, & counted ####" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "v = [1,3, 2, 3, 4, 1.3]\n", "v.sort() ; print(v)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "If there isn't a natural way to compare elements, the sort will fail.\n", "\n", "`reverse` is a keyword of the `.sort()` method" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import math\n", "v = [1,3, 2, 3, 4, math.pi]\n", "v.sort() ; print(v)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "v.sort(reverse=True) ; print(v)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "v.sort?" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "`.sort()` changes the the list in place " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "v.index(4) ## lookup the index of the entry 4" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "v.index(3)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "v.count(3)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "v.insert(0,\"it's full of stars\") ; print(v)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "v.remove(3.0) ; print(v)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "  " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### IPython is your new best friend ##\n", "\n", "1. Type `v.` then the Tab button\n", "\n", "2. Type `v.re` then the Tab button\n", "\n", "3. Type `v.remove?`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "## try it here" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "  " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### List ###\n", "#### iteration ####" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "x = 1\n", "a = ['cat', 'window', 'defenestrate']\n", "for x in a:\n", " print(x, len(x))\n", " if x == \"cat\":\n", " a.append(\"?\")\n", "print(x)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "for i,x in enumerate(a):\n", " print(i, x, len(x))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "b = enumerate(a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(b.__next__())" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "for x in a:\n", " print(x, end=',')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "The syntax for iteration is... \n", "\n", " for variable_name in iterable:\n", " # do something with variable_name" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "The `range()` function" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "x = list(range(4)) ; print(x)\n", "total = 0\n", "for val in range(4):\n", " total += val\n", " print(\"By adding \" + str(val) + \\\n", " \" the total is now \" + str(total))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "\n", "`range`([`start`,] `stop`[, `step`])\n", "→ list of integers" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "total = 0\n", "for x in range(1,10,2):\n", " total += x\n", " print(\"By adding \" + str(x) + \\\n", " \" the total is now \" + str(total))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "a = ['Mary', 'had', 'a', 'little', 'lamb']\n", "for i in range(len(a)):\n", " print(i, a[i])" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "  " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Sets ###\n", "#### denoted with a curly braces ####" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "{1,2,3,\"bingo\"}" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "print(type({1,2,3,\"bingo\"}))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "print(type({}))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "print(type(set()))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "set([\"spamIam\"])" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "sets have unique elements. They can be\n", "compared, differenced, unionized, etc." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "a = set(\"sp\") ; b = set(\"am\"); print(a) ; print(b)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "c = set([\"m\",\"a\"])\n", "c == b" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "\"p\" in a" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "\"ps\" in a" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "q = set(\"spamIam\")\n", "a.issubset(q)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "a | b" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "q - (a | b)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "q & (a | b)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Like lists, we can use as (unordered) buckets\n", "`.pop()` gives us a random element" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "# this is pretty volitile...wont be the same\n", "# order on all machines\n", "for i in q & (a | b):\n", " print(i, end=' ') " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "q.remove(\"a\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "q.pop()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "print(q.pop())\n", "print(q.pop())" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "print(q.pop())\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(q)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "q.pop()" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "  " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Dictionaries ##\n", "denoted with a curly braces and colons" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "d = {\"favorite cat\": None, \"favorite spam\": \"all\"}" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "these are key: value, key: value, ..." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "print(d[\"favorite cat\"])\n", "d[0] ## this is not a list and you dont have a keyword = 0" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "e = {\"favorite cat\": None, \"favorite spam\": \"all\", \\\n", " 1: 'loneliest number'}\n", "e[1] == 'loneliest number'" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "dictionaries are **UNORDERED***. \n", ">You cannot assume that one key comes before or after another\n", "\n", "* you can use a special type of ordered dict if you really need it:\n", "\n", "https://docs.python.org/3.1/whatsnew/3.1.html#pep-372-ordered-dictionaries" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### 4 ways to make a Dictionary ###" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# number 1...you've seen this\n", "d = {\"favorite cat\": None, \"favorite spam\": \"all\"}" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# number 2\n", "d = dict(one = 1, two=2,cat = 'dog') ; print(d)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# number 3 ... just start filling in items/keys\n", "d = {} # empty dictionary\n", "d['cat'] = 'dog'\n", "d['one'] = 1\n", "d['two'] = 2\n", "d" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# number 4... start with a list of tuples\n", "mylist = [(\"cat\",\"dog\"), (\"one\",1),(\"two\",2)]\n", "print(dict(mylist))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "dict(mylist) == d" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "list(d)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "  " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### Dictionaries: they can be complicated (in a good way) ####" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "d = {\"favorite cat\": None, \"favorite spam\": \"all\"}" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "d = {'favorites': {'cat': None, 'spam': 'all'}, \\\n", " 'least favorite': {'cat': 'all', 'spam': None}}\n", "print(d['least favorite']['cat'])" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "remember: the backslash (\\) allows you to across break lines. Not technically needed when defining a dictionary or list" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "phone_numbers = {'family': [('mom','642-2322'),('dad','534-2311')],\\\n", " 'friends': [('Billy','652-2212')]}" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "for group_type in ['friends','family']:\n", " print(\"Group\",group_type,\":\",sep=\" \")\n", " for info in phone_numbers[group_type]:\n", " print(\"\\t\",info[0],info[1],sep=\" \")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# this will return a list, but you dont know in what order! \n", "list(phone_numbers.keys())" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "list(phone_numbers.values())[-1]" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "  " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "`.keys()` and `.values()`: are called `methods` on dictionaries" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "for group_type in list(phone_numbers.keys()):\n", " print(\"Group\",group_type,\":\",sep=\" \")\n", " for info in phone_numbers[group_type]:\n", " print(\"\\t\",info[0],info[1],sep=\" \")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "we cannot ensure ordering here of the groups" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "groups = list(phone_numbers.keys())\n", "groups.sort()\n", "for group_type in groups:\n", " print(\"Group\",group_type,\":\",sep=\" \")\n", " for info in phone_numbers[group_type]:\n", " print(\"\\t\",info[0],info[1],sep=\" \")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "`.items()` is a handy method,\n", "returning key,value pairs with each iteration" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "for group_type, vals in phone_numbers.items():\n", " print(\"Group\",group_type,\":\",sep=\" \")\n", " for info in vals:\n", " print(\"\\t\",info[0],info[1],sep=\" \")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Some examples of getting values:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "phone_numbers['co-workers']" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "'co-workers' in phone_numbers" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "print(phone_numbers.get('co-workers'))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "skip" } }, "outputs": [], "source": [ "phone_numbers.get('friends') == phone_numbers['friends']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Defaults in a `get`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "print(phone_numbers.get('co-workers',\"all alone\"))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "phone_numbers.get?" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "  " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "  " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### setting values ####\n", "\n", "you can edit the values of keys and also `.pop()` & `del` to remove certain keys" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "\"BFFs\" in phone_numbers.keys()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# add to the friends list\n", "phone_numbers['friends'].append((\"Marsha\",\"232-1121\"))\n", "print(phone_numbers)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "## billy's number changed\n", "phone_numbers['friends'][0][1] = \"532-1521\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "phone_numbers['friends'][0] = (\"Billy\",\"532-1521\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "## I lost all my friends preparing for this Python class\n", "phone_numbers['friends'] = [] # sets this to an empty list" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "## remove the friends key altogether\n", "print(phone_numbers.pop('friends'))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "print(phone_numbers)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "del phone_numbers['family']" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "print(phone_numbers)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "  " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "`.update()` method is very handy, like `.append()` for lists" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "phone_numbers.update({\"friends\": [(\"Billy's Brother, Bob\", \"532-1521\")]})\n", "print(phone_numbers)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "  " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Casting Back and Forth ###" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "a = [1,2,3,(\"b\",1),(\"b\",1)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "b = tuple(a) ; print(b)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "print(list(b))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "set(a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "list(set(\"spam\"))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "> casting only affects top-level structure, not the elements " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## List Comprehension ##\n", "\n", "You can create lists \"on the fly\" by asking simple questions of other iterateable data structures" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "example: I want a list of all numbers from 0 - 100 whose lowest two bits are both one (e.g., 3, 7, ...) but is not divisible by 11" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "mylist = []\n", "for num in range(101):\n", " if (num & 2) and (num & 1) and (num % 11 != 0.0):\n", " mylist.append(num)\n", "print(mylist)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "mylist=[num for num in range(101) if (num & 2) \\\n", " and (num & 1) and (num % 11 != 0.0)]\n", "print(mylist)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "example: I want a list of all mesons whose masses are between 100 and 1000 MeV" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "particles = \\\n", "[{\"name\":\"π+\" ,\"mass\": 139.57018}, {\"name\":\"π0\" ,\"mass\": 134.9766}, \n", " {\"name\":\"η5\" ,\"mass\": 47.853}, {\"name\":\"η′(958)\",\"mass\": 957.78}, \n", " {\"name\":\"ηc(1S)\", \"mass\": 2980.5}, {\"name\": \"ηb(1S)\",\"mass\": 9388.9}, \n", " {\"name\":\"K+\", \"mass\": 493.677}, {\"name\":\"K0\" ,\"mass\": 497.614}, \n", " {\"name\":\"K0S\" ,\"mass\": 497.614}, {\"name\":\"K0L\" ,\"mass\": 497.614},\n", " {\"name\":\"D+\" ,\"mass\": 1869.62}, {\"name\":\"D0\" ,\"mass\": 1864.84},\n", " {\"name\":\"D+s\" ,\"mass\": 1968.49}, {\"name\":\"B+\" ,\"mass\": 5279.15},\n", " {\"name\":\"B0\" ,\"mass\": 5279.5}, {\"name\":\"B0s\" ,\"mass\": 5366.3},\n", " {\"name\":\"B+c\" ,\"mass\": 6277}]\n", "\n", "# data source: http://en.wikipedia.org/wiki/List_of_mesons\n", "\n", "my_mesons = [ (x['name'],x['mass']) for \\\n", " x in particles if x['mass'] <= 1000.0 and x['mass'] >= 100.0]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# get the average\n", "tot = 0.0\n", "for x in my_mesons: tot += x[1]\n", "print(\"The average meson mass in this range is \" + str(tot/len(my_mesons)) \\\n", " + \" MeV/c^2.\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(\"The average meson mass in this range is \" + str(round(tot/len(my_mesons),2)) \\\n", " + \" MeV/c^2.\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "my_mesons[0][0]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "bytes(my_mesons[0][0],encoding=\"utf-8\")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "  " ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "## Breakout Session Work" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Consider the following data (file: `airline.py`):" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# %load airline.py\n", "airports = {\"DCA\": \"Washington, D.C.\", \"IAD\": \"Dulles\", \"LHR\": \"London-Heathrow\", \\\n", " \"SVO\": \"Moscow\", \"CDA\": \"Chicago-Midway\", \"SBA\": \"Santa Barbara\", \"LAX\": \"Los Angeles\",\\\n", " \"JFK\": \"New York City\", \"MIA\": \"Miami\", \"AUM\": \"Austin, Minnesota\"}\n", " \n", "# airline, number, heading to, gate, time (decimal hours) \n", "flights = [(\"Southwest\",145,\"DCA\",1,6.00),(\"United\",31,\"IAD\",1,7.1),(\"United\",302,\"LHR\",5,6.5),\\\n", " (\"Aeroflot\",34,\"SVO\",5,9.00),(\"Southwest\",146,\"CDA\",1,9.60), (\"United\",46,\"LAX\",5,6.5),\\\n", " (\"Southwest\",23,\"SBA\",6,12.5),(\"United\",2,\"LAX\",10,12.5),(\"Southwest\",59,\"LAX\",11,14.5),\\\n", " (\"American\", 1,\"JFK\",12,11.3),(\"USAirways\", 8,\"MIA\",20,13.1),(\"United\",2032,\"MIA\",21,15.1),\\\n", " (\"SpamAir\",1,\"AUM\",42,14.4)]\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1. print out a schedule organized by airline:\n", "\n", "
\n",
    "Flight          Destination          Gate   Time\n",
    "--------------------------------------------------\n",
    "Aeroflot 34    Moscow              \t5   9.0\n",
    "American 1     New York City       \t12  11.3\n",
    "Southwest 23   Santa Barbara       \t6   12.5\n",
    "Southwest 59   Los Angeles         \t11  14.5\n",
    "...\n",
    "
\n", "\n", "### 2. print out a schedule organized by time\n", "\n", "*hint: you'll need to do a manual sorting on the last element of each flight element, before beginning the printing loop*" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\"Will" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "py3k" }, "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.5.2" } }, "nbformat": 4, "nbformat_minor": 0 }