{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Principal built-in types in Python (Python主要内置数据类型)\n", "\n", "- numerics: int, float, long, complex\n", "- sequences: str, unicode, **list**, **tuple**, bytearray, buffer, xrange\n", "- mappings: **dict**\n", "- files: \n", "- classes:\n", "- instances:\n", "- exceptions:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Lists (列表)\n", "\n", "The list data type has some more methods. Here are all of the methods of list objects in **Python 3**:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**list.append(x)**\n", "\n", " Add an item to the end of the list. Equivalent to a[len(a):] = [x]." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "a = [1, 2, 4, 5,8, 100 ,1005]" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 4, 5, 8, 100, 1005, 2]" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.append(2)\n", "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**list.extend(L)**\n", "\n", "Extend the list by appending all the items in the given list. Equivalent to a[len(a):] = L." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 4, 5, 8, 100, 1005, 2, 'Feng', 'Li', 'Love']" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b = [\"Feng\", \"Li\", \"Love\"]\n", "a.extend(b)\n", "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**list.insert(i, x)**\n", "\n", "Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x)." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 'Hello', 2, 4, 5, 8, 100, 1005, 2, 'Feng', 'Li', 'Love']" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.insert(1,\"Hello\")\n", "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**list.remove(x)**\n", "\n", "Remove the first item from the list whose value is x. It is an error if there is no such item.\n", "\n", "**list.pop([i])**\n", "\n", "Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. **(The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)**\n", "\n", "**list.clear()**\n", "\n", "Remove all items from the list. Equivalent to del a[:]." ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "[1, 'Hello', 4, 5, 8, 100, 1005, 2, 'Feng', 'Li', 'Love']" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.pop(2)\n", "a" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 'Hello', 4, 5, 8, 100, 1005, 2, 'Feng', 'Li']" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.pop()\n", "a" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 4, 5, 8, 100, 1005, 2, 'Feng', 'Li']" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.remove(\"Hello\")\n", "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**list.index(x)**\n", "\n", "Return the index in the list of the first item whose value is x. It is an error if there is no such item.\n", "\n", "**list.count(x)**\n", "\n", "Return the number of times x appears in the list.\n", "\n", "**list.sort()**\n", "\n", "Sort the items of the list in place." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "a.append(\"Love\")" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "11" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.index(\"Love\")" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.count(\"Love\")" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 7, 14]" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b = [1,7,2,14] \n", "b.sort()\n", "b" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**list.reverse()**\n", "\n", "Reverse the elements of the list in place.\n", "\n", "**list.copy()**\n", "\n", "Return a shallow copy of the list. Equivalent to a[:]." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['Love', 'Li', 'Feng', 2, 1005, 100, 8, 5, 4, 1]" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.reverse()\n", "a" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "scrolled": false }, "outputs": [ { "data": { "text/plain": [ "['Love', 'Li', 'Feng', 2, 1005, 100, 8, 5, 4, 1]" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b = a.copy()\n", "b" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**The del statement**\n", " \n", "There is a way to remove an item from a list given its index instead of its value: the del statement. This differs from the `pop()` method which returns a value. The `del` statement can also be used to remove slices from a list or clear the entire list\n", " " ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 'Hello', 2, 4, 5, 8, 100, 1005, 2, 'Feng', 'Li', 'Love', 'Love']" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 'Hello', 4, 5, 8, 100, 1005, 2, 'Feng', 'Li', 'Love', 'Love']" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "del a[2]\n", "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`del` can also be used to delete entire variables" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "scrolled": false }, "outputs": [], "source": [ "del a\n", "# a will not be there" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Variables and pass-by-reference (变量的按址传递)\n", "\n", "When assigning a variable (or name) in Python, you are creating a **reference** to the object on the right hand side of the equals sign." ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3, 4]\n", "[1, 2, 3, 4]\n" ] } ], "source": [ "a = [1,2,3,4]\n", "b = a\n", "print(a)\n", "print(b)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3, 4, 100]\n", "[1, 2, 3, 4, 100]\n" ] } ], "source": [ "a.append(100)\n", "print(a)\n", "print(b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Understanding the semantics of references in Python and when, how, and why data is copied is especially critical when working with larger data sets in Python. If you really need to make hard copy, use method like `list.copy()`" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3, 4, 100, 23232]\n", "[1, 2, 3, 4, 100]\n", "[1, 2, 3, 4, 100]\n" ] } ], "source": [ "c1 = a.copy()\n", "c2 = a[:]\n", "a.append(23232)\n", "print(a)\n", "print(c1)\n", "print(c2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using Lists as Stacks (把列表当作堆栈使用)\n", "\n", "The list methods make it very easy to use a list as a **stack**, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append(). To retrieve an item from the top of the stack, use pop() without an explicit index" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "collapsed": true }, "outputs": [], "source": [ "stack = [3, 4, 5]" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "[3, 4, 5, 2]" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "stack.append(2)\n", "stack" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "[3, 4, 5]" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "stack.pop()\n", "stack" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using Lists as Queues (把列表当作队列使用)\n", "\n", "It is also possible to use a list as a **queue**, where the first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose.\n", "\n", "To implement a queue, use _collections.deque_ which was designed to have fast appends and pops from both ends. For example:" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "deque(['Eric', 'John', 'Michael', 'Terry', 'Graham'])" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from collections import deque\n", "queue = deque([\"Eric\", \"John\", \"Michael\"])\n", "queue.append(\"Terry\") # Terry arrives\n", "queue.append(\"Graham\") # Graham arrives\n", "queue " ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "deque(['Michael', 'Terry', 'Graham'])" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "queue.popleft() # The first to arrive now leaves\n", "queue.popleft() # The second to arrive now leaves\n", "queue " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## List Comprehensions (列表推导式)\n", "\n", "List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition." ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "squares = [] # the usual way\n", "for x in range(10):\n", " squares.append(x**2)\n", "squares" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can calculate the list of squares without any side effects using the following. This is very similar to R programming language's apply type functions." ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "scrolled": false }, "outputs": [ { "data": { "text/plain": [ "[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "squares = [x**2 for x in range(10)]\n", "squares" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which eventually did this" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1.0,\n", " 2.718281828459045,\n", " 7.38905609893065,\n", " 20.085536923187668,\n", " 54.598150033144236,\n", " 148.4131591025766,\n", " 403.4287934927351,\n", " 1096.6331584284585,\n", " 2980.9579870417283,\n", " 8103.083927575384]" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import math\n", "squares = list(map(lambda x: math.exp(x), range(10)))\n", "squares" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it." ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "which is equivalent to:" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "combs = []\n", "for x in [1,2,3]:\n", " for y in [3,1,4]:\n", " if x != y:\n", " combs.append((x, y))\n", "\n", "combs" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Nested List Comprehensions (内嵌列表推导式)\n", "\n", "The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension." ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "matrix = [[1, 2, 3, 4],\n", " [5, 6, 7, 8],\n", " [9, 10, 11, 12]]\n", "matrix" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The following list comprehension will transpose rows and columns:" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "[[row[i] for row in matrix] for i in range(4)] " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "the magic behind this was" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "transposed = []\n", "for i in range(4):\n", " transposed.append([row[i] for row in matrix])\n", "\n", "transposed" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the real world, you should prefer built-in functions to complex flow statements. The zip() function would do a great job for this use case:" ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(zip(*matrix))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Tuples (元组)\n", "\n", "A tuple consists of a number of values separated by commas" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "12345" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "t = 12345, 54321, 'hello!'\n", "t[0]" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(12345, 54321, 'hello!')" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "t" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Tuples may be nested and tuples are immutable, but they can contain mutable objects." ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "u = t, (1, 2, 3, 4, 5)\n", "u" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "([1, 2, 3], [3, 2, 1])" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "v = ([1, 2, 3], [3, 2, 1])\n", "v" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Note** On output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expression). It is not possible to assign to the individual items of a tuple, however it is possible to create tuples which contain mutable objects, such as lists." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Dictionaries (字典)\n", "\n", "Unlike sequences, which are indexed by a range of numbers, **dictionaries** are indexed by _keys_. Dictionaries are sometimes found in other languages as ``associative memories'' or ``associative arrays''. \n", "\n", "The keys can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can't use lists as keys.\n", "\n", "It is best to think of a dictionary as an unordered set of `key:value` pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of `key:value` pairs within the braces adds initial `key:value` pairs to the dictionary; this is also the way dictionaries are written on output.\n", "\n", "The main operations on a dictionary are storing a value with some key and extracting the value given the key. \n" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'guido': 4127, 'jack': 4098, 'sape': 4139}\n" ] } ], "source": [ "tel = {'jack': 4098, 'sape': 4139}\n", "tel['guido'] = 4127\n", "print(tel)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `dict()` constructor builds dictionaries directly from sequences of `key:value` pairs:" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'guido': 4127, 'jack': 4098, 'sape': 4139}" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'guido': 4127, 'jack': 4098, 'sape': 4139}" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dict(sape=4139, guido=4127, jack=4098)" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "['guido', 'jack', 'sape']" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(tel.keys())" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "['guido', 'jack', 'sape']" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sorted(tel.keys())" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'guido' in tel" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'jack' not in tel" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is also possible to delete a `key:value` pair with del. If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key.\n" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "scrolled": true }, "outputs": [ { "ename": "KeyError", "evalue": "'sape'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mKeyError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;32mdel\u001b[0m \u001b[0mtel\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'sape'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 2\u001b[0m \u001b[0mtel\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mKeyError\u001b[0m: 'sape'" ] } ], "source": [ "del tel['sape']\n", "tel" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`dict` comprehensions can be used to create dictionaries from arbitrary key and value expressions:" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{2: 4, 4: 16, 6: 36}" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "{x: x**2 for x in (2, 4, 6)}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Sets (集合)\n", "\n", "A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.\n", "\n", "Curly braces `{}` or the `set()` function can be used to create sets. Note: to create an empty set you have to use `set()`, not `{}`; the latter creates an empty dictionary." ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'apple', 'pear', 'orange', 'banana'}\n" ] } ], "source": [ "basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}\n", "print(basket) # show that duplicates have been removed " ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'orange' in basket " ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'c', 'b', 'a', 'd', 'r'}\n", "{'c', 'm', 'l', 'a', 'z'}\n" ] } ], "source": [ "a = set('abracadabra')\n", "b = set('alacazam')\n", "print(a)\n", "print(b)" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'b', 'd', 'r'}" ] }, "execution_count": 49, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a - b" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a', 'b', 'c', 'd', 'l', 'm', 'r', 'z'}" ] }, "execution_count": 50, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a | b" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a', 'c'}" ] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a & b" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'b', 'd', 'l', 'm', 'r', 'z'}" ] }, "execution_count": 52, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a ^ b # XOR: exclusive OR" ] }, { "cell_type": "code", "execution_count": 53, "metadata": { "collapsed": true }, "outputs": [], "source": [ "a = {x for x in 'abracadabra' if x not in 'abc'} # set comprehensions" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'d', 'r'}" ] }, "execution_count": 54, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Looping (循环)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method." ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "robin the brave\n", "gallahad the pure\n" ] } ], "source": [ "knights = {'gallahad': 'the pure', 'robin': 'the brave'}\n", "for k, v in knights.items():\n", " print(k, v)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the `enumerate()` function." ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 tic\n", "1 tac\n", "2 toe\n" ] } ], "source": [ "for i, v in enumerate(['tic', 'tac', 'toe']):\n", " print(i, v)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To loop over two or more sequences at the same time, the entries can be paired with the `zip()` function." ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "What is your name? It is lancelot.\n", "What is your quest? It is the holy grail.\n", "What is your favorite color? It is blue.\n" ] } ], "source": [ "questions = ['name', 'quest', 'favorite color']\n", "answers = ['lancelot', 'the holy grail', 'blue']\n", "for q, a in zip(questions, answers):\n", " print('What is your {0}? It is {1}.'.format(q, a))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the `reversed()` function." ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "9\n", "7\n", "5\n", "3\n", "1\n" ] } ], "source": [ "for i in reversed(range(1, 10, 2)):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To loop over a sequence in sorted order, use the `sorted()` function which returns a new sorted list while leaving the source unaltered." ] }, { "cell_type": "code", "execution_count": 59, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "apple\n", "banana\n", "orange\n", "pear\n" ] } ], "source": [ "basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']\n", "for f in sorted(set(basket)):\n", " print(f)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To change a sequence you are iterating over while inside the loop (for example to duplicate certain items), it is recommended that you first make a copy. Looping over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['defenestrate', 'cat', 'window', 'defenestrate']" ] }, "execution_count": 60, "metadata": {}, "output_type": "execute_result" } ], "source": [ "words = ['cat', 'window', 'defenestrate']\n", "for w in words[:]: # Loop over a slice copy of the entire list.\n", " if len(w) > 6:\n", " words.insert(0, w)\n", "\n", "words" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "words2 = ['cat', 'window', 'defenestrate']\n", "for w in words2: # No copies.\n", " if len(w) > 6:\n", " words2.insert(0, w)\n", "\n", "words2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Conditions (条件判别)\n", "\n", "The conditions used in while and if statements can contain any operators, not just comparisons.\n", "\n", "**The comparison operators** in and not in check whether a value occurs (does not occur) in a sequence. The operators **is** and **is not** compare whether two objects are really the same object; this only matters for mutable objects like lists. All comparison operators have the same priority, which is lower than that of all numerical operators.\n", "\n", "Comparisons can be **chained**. For example, a < b == c tests whether a is less than b and moreover b equals c.\n", "\n", "Comparisons may be combined using the **Boolean operators**, **and** and **or**, and the outcome of a comparison (or of any other Boolean expression) may be negated with **not**. These have lower priorities than comparison operators; between them, **not** has the highest priority and **or** the lowest, so that _A and not B or C_ is equivalent to ((A and (not B)) or C). As always, parentheses can be used to express the desired composition.\n", "\n", "**The Boolean operators** and and or are so-called short-circuit operators: their arguments are evaluated from left to right, and evaluation stops as soon as the outcome is determined. For example, if A and C are true but B is false, A and B and C does not evaluate the expression C. When used as a general value and not as a Boolean, the return value of a short-circuit operator is the last evaluated argument.\n", "\n", "\n", " Keyword (Scalar) | Function | Bitwise | True if . . .\n", " -----------------------------------------------------------------\n", " and | logical_and() | & | Both True\n", " or | logical_or() | | | Either or Both True\n", " not | logical_not() | ~ | Not True\n", " | logical_xor() | ^ | One True and One False\n", " \n", " \n", " \n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Logical Operators (逻辑算子)\n", "\n", "The core logical operators are\n", "\n", "- **Greater than**: >, greater()\n", "- **Greater than or equal to**: >=, greater_equal()\n", "- **Less than**: <, less()\n", "- **Less than or equal to**: <= less_equal()\n", "- **Equal to**: == equal()\n", "- **Not equal to**: != not_equal\n", "\n", "\n", "All comparisons are done element-by-element and return either True or False. Note that in Python, unlike C, assignment cannot occur inside expressions. it avoids a common class of problems encountered in C programs: typing `=` in an expression when `==` was intended.\n", "\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Multiple tests (多重测试)\n", "\n", "The functions **all** and **any** take logical input and are self-descriptive. all returns True if all logical elements in an array are 1. If all is called without any additional arguments on an array, it returns True if all\n", "elements of the array are logical true and 0 otherwise. any returns logical(True) if any element of an array\n", "is True ." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## is* (is开头的测试)\n", "\n", "A number of special purpose logical tests are provided to determine if an array has special characteristics.\n", "Some operate element-by-element and produce an array of the same dimension as the input while other\n", "produce only scalars. These functions all begin with is .\n", "\n", " isnan\n", " isinf\n", " isfinite\n", " isposfin , isnegfin\n", " isreal\n", " iscomplex\n", " isreal\n", " is_string_like\n", " is_numlike\n", " isscalar\n", " isvector" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.6.4+" } }, "nbformat": 4, "nbformat_minor": 1 }