{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 数据结构 - 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "数据结构是计算机存储、组织数据的方式,简单来说是指相互之间存在一种或多种特定关系的数据元素的集合。\n", "\n", "Python中的数据结构设计的非常巧妙,使用起来非常方便,几乎绝大多数的数据结构都可以通过`list`, `tuple`, `dict`, `string`, `set`等表示,因此用户几乎不需要自己定义数据结构,仅仅使用Python内置的数据结构即可实现非常复杂的算法和操作。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. 列表" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "列表是最常用的数据结构。可以把它看作用方括号括起来的数据序列,数据之间用逗号分隔。这些数据都可以通过调用其索引值来访问。\n", "\n", "`list`的声明只需将变量等同于`[ ]`或`list`即可。" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "a = []" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "print(type(a))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "可以直接将数据序列分配给列表x,如下所示。" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['apple', 'orange', 'peach']\n" ] } ], "source": [ "x = ['apple', 'orange', 'peach']\n", "print(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1.1 索引" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "在Python中,索引从`0`开始。因此,现在包含两个元素的列表`x`的apple索引值为`0`,orange索引值为`1`。" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'apple'" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x[0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "索引也可以按照相反的顺序进行。这是最后一个可以被首先访问的元素。这里,索引从`-1`开始。因此,索引`-1`对应是橙色,索引`-2`对应的是苹果。" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'peach'" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x[-1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "正如你可能猜到的一样,x[0] = x[-2], x[1] = x[-1]。这个概念可以扩展到更多包含元素的列表。" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": true }, "outputs": [], "source": [ "y = ['carrot','potato']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "在这里我们已经声明过两个列表`x`和`y`每一个包含自己的数据。现在,这两个列表可以再一次被放入另一个也具有自己的数据的列表`z`中。列表中的这个列表被称为`嵌套列表`,这就是数组的声明方式,我们将在后面看到。**这是和很多其他计算机语言不同的地方,不要求列表的元素是相同类型,因此编程的时候会非常方便,这也是为什么Python对人类比较友好**" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[['apple', 'orange', 'peach'], ['carrot', 'potato'], 'Test']\n" ] } ], "source": [ "z = [x,y, 'Test']\n", "print(z)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'orange'" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "z[0][1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "如何获得嵌套列表中的某个元素?让我们在上述嵌套列表中获得数据'apple'为例。\n", "* 首先在索引为0处,有一个列表`['apple','orange']` 而在索引为1处有另外一个列表`['carrot','potato']` 。\n", "* 因此z[0] 应该给我们第一个包含'apple'的列表。" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['apple', 'orange', 'peach']\n" ] } ], "source": [ "z1 = z[0]\n", "print(z1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "现在观察z1并不是一个嵌套列表,因此为了获得'apple',z1的索引应该为0。" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'apple'" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "z1[0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "在python中,你可以通过每次并排写索引值来访问“apple”,而不是像上面那样做。" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'apple'" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "z[0][0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "如果列表中有一个列表,那么您可以通过执行 z[ ][ ][ ] 来访问最里面的值。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1.2 切片" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "索引只限于访问单个元素,而切片则是访问列表内的一系列数据。换句话说,`切片`返回的是一个列表。\n", "\n", "切片是通过定义切片列表中需要的父列表中的第一个元素和最后一个元素的索引值来完成的。它被写成parentlist[a: b],其中`a`,`b`是父列表的索引值。如果`a`或`b`未定义,则认为该索引值是`a`未定义时的第一个值,以及`b`未定义时的最后一个值。" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[3, 2, 3]\n", "[2, 3, 2, 3, 4, 5, 6, 7, 8, 9]\n", "[2, 3, 2, 3, 4, 5, 6, 7, 8, 9]\n", "[2, 3, 2, 3, 4, 5, 6, 7, 8, 9]\n" ] } ], "source": [ "num = [2,3,2,3,4,5,6,7,8,9]\n", "print(num[1:4])\n", "print(num[0:])\n", "print(num[:])\n", "print(num)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2, 3, 2, 3]\n", "[4, 5, 6, 7, 8, 9]\n" ] } ], "source": [ "print(num[0:4])\n", "print(num[4:])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "您还可以使用固定长度或步长对父列表进行切片。" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[2, 3, 6]" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "num[:9:3]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1.3 列表的内置函数" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "为了找到列表的长度或者列表中元素的数量,我们可以使用**len( )**。" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "10" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(num)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "如果列表包含所有的整数元素,那么 **min( )** 和 **max( )** 给出列表中的最大值和最小值。" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2, 3, 2, 3, 4, 5, 6, 7, 8, 9]\n" ] }, { "data": { "text/plain": [ "2" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "print(num)\n", "min(num)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "9" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "max(num)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "列表可以通过添加\"`+`\"来连接。生成的列表将包含添加的列表的所有元素。结果列表将不是嵌套列表。" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 5, 4, 7]" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "[1,2,3] + [5,4,7]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "可能会出现这样的需求,您可能需要检查预定义列表中是否存在特定的元素。考虑下面的列表。" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "collapsed": true }, "outputs": [], "source": [ "names = ['Earth','Air','Fire','Water']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "检查“Fire”和“Rajath”是否出现在列表名称中。传统的方法是使用for循环遍历列表并使用if条件。但在python中,你可以使用\" a在b中\"的概念,如果a在b中出现,它会返回\"True\"如果不是,它会返回\"False\"" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'Fir' in names" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'Fire' in names" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'fire' in names" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "在一个有字符串作为元素的列表中,**max( )** 和 **min( )** 可以使用。**max( )** 会返回一个ASCII码最大的元素而最小的元素会在使用**min( )** 返回。注意,每次只考虑每个元素的第一个索引,如果它们的值相同,则考虑第二个索引,依此类推。" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "collapsed": true }, "outputs": [], "source": [ "mlist = ['bzaa','ds','nc','az','z','klm']" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "z\n", "az\n" ] } ], "source": [ "print(max(mlist))\n", "print(min(mlist))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "这里考虑每个元素的第一个索引,因此z有最高的ASCII值,因此它被返回,最小的ASCII值是a。但是如果数字被声明为字符串呢?" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "collapsed": true }, "outputs": [], "source": [ "nlist = ['1','94','93','1000']" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "94\n", "1\n" ] } ], "source": [ "print(max(nlist))\n", "print(min(nlist))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "即使数字是在字符串中声明的,也会考虑每个元素的第一个索引,并相应地返回最大值和最小值。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "但是如果你想找到给予字符串长度的 **max( )** 字符串元素,那么我们要在 **max( )** 和 **min( )** 中声明参数'key=len'。" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Earth\n", "Jet\n" ] } ], "source": [ "names = ['Earth','Jet', 'Air','Fire','Water']\n", "print(max(names, key=len))\n", "print(min(names, key=len))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "但是即使'Water'的长度为5。**max()** 或 **min()** 函数返回第一个元素当两个或者多个元素具有相同的长度。\n", "\n", "可以使用任何其他内建函数或lambda函数(后面将讨论)来代替len。\n", "\n", "通过使用**list()** 函数,一个字符串可以被转化成列表。" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['h', 'e', 'l', 'l', 'o']" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list('hello')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**append( )** 被用来在列表的最后添加一个元素。" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "collapsed": true }, "outputs": [], "source": [ "lst = [1,1,4,8,7]" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 1, 4, 8, 7, 1]\n" ] } ], "source": [ "lst.append(1)\n", "print(lst)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**count( )** 用于计算列表中出现的特定元素的数量。" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lst.count(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**append( )** 函数也可以被用来在末尾添加一整个列表。观察可以发现最终得到的列表是嵌套列表。" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "collapsed": true }, "outputs": [], "source": [ "lst1 = [5,4,2,8]" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 1, 4, 8, 7, 1, [5, 4, 2, 8], [5, 4, 2, 8]]\n" ] }, { "data": { "text/plain": [ "[1, 1, 4, 8, 7, 1, [5, 4, 2, 8], [5, 4, 2, 8], 5, 4, 2, 8]" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lst.append(lst1)\n", "print(lst)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "但是如果嵌套列表不是需要的,那么可以使用**extend()** 函数。" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 1, 4, 8, 7, 1, [5, 4, 2, 8], [5, 4, 2, 8], 5, 4, 2, 8]\n" ] } ], "source": [ "lst.extend(lst1)\n", "print(lst)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**index( )** 被用来找到一个特殊元素的索引值。注意如果有许多个元素具有相同的值那么元素第一个索引值会被返回。" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lst.index(1)" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "ename": "ValueError", "evalue": "999 is not in list", "output_type": "error", "traceback": [ "\u001b[0;31m------------------------------------------\u001b[0m", "\u001b[0;31mValueError\u001b[0mTraceback (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[0mlst\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mindex\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m999\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mValueError\u001b[0m: 999 is not in list" ] } ], "source": [ "lst.index(999)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**insert(x,y)** 用于在指定的索引值x处插入元素y。**append( )** 函数使得它只能插在最后。" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 1, 4, 8, 7, 'name', 1, [5, 4, 2, 8], [5, 4, 2, 8], 5, 4, 2, 8]\n" ] } ], "source": [ "lst.insert(5, 'name')\n", "print(lst)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**insert(x,y)** 插入但不替换元素。如果希望用另一个元素替换该元素,只需将值赋给该特定索引。" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 1, 4, 8, 7, 'Python', 1, [5, 4, 2, 8], [5, 4, 2, 8], 5, 4, 2, 8]\n" ] } ], "source": [ "lst[5] = 'Python'\n", "print(lst)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**pop( )** 函数返回列表中的最后一个元素。这类似于堆栈的操作。因此,说列表可以作为堆栈使用是正确的。" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 1, 4, 8, 7, 'Python', 1, [5, 4, 2, 8], [5, 4, 2, 8], 5, 4, 2]" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lst.pop()\n", "lst" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "可以指定索引值来弹出与该索引值对应的元素。" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 42, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lst.pop(2)" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 1, 8, 7, 'Python', 1, [5, 4, 2, 8], [5, 4, 2, 8], 5, 4, 2]\n" ] }, { "data": { "text/plain": [ "4" ] }, "execution_count": 43, "metadata": {}, "output_type": "execute_result" } ], "source": [ "print(lst)\n", "lst.pop(-2)" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 1, 8, 7, 'Python', 1, [5, 4, 2, 8], [5, 4, 2, 8], 5, 2]\n" ] } ], "source": [ "print(lst)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**pop( )** 用于根据可分配给变量的元素的索引值来删除元素。还可以通过使用**remove()** 函数指定元素本身来删除元素。" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "ename": "ValueError", "evalue": "list.remove(x): x not in list", "output_type": "error", "traceback": [ "\u001b[0;31m------------------------------------------\u001b[0m", "\u001b[0;31mValueError\u001b[0mTraceback (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[0mlst\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mremove\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'Python'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 2\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlst\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mValueError\u001b[0m: list.remove(x): x not in list" ] } ], "source": [ "lst.remove('Python')\n", "print(lst)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "可以替代 **remove** 但是使用索引值的函数是 **del**。" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, [5, 4, 2, 8], 5, 2]\n", "[1, 5, 2]\n" ] } ], "source": [ "print(lst)\n", "del lst[1]\n", "print(lst)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "可以使用**reverse()** 函数反转列表中出现的所有元素。" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2, 5, 1]\n" ] } ], "source": [ "lst.reverse()\n", "print(lst)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "注意嵌套列表 [5,4,2,8] 被视为父列表lst的单个元素。因此在嵌套列表里的元素是不可以被翻转的。\n", "\n", "Python提供了内置函数 **sort( )** 去按升序排列元素。" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 4, 8, 8, 10]\n" ] } ], "source": [ "lst = [1, 4, 8, 8, 10]\n", "lst.sort()\n", "print(lst)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "对于降序,因为默认情况下反向条件为False。因此,将其更改为True将按降序排列元素。" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "must use keyword argument for key function", "output_type": "error", "traceback": [ "\u001b[0;31m------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0mTraceback (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[0mlst\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msort\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;32mTrue\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 2\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlst\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mTypeError\u001b[0m: must use keyword argument for key function" ] } ], "source": [ "lst.sort(reverse=True)\n", "print(lst)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "相似地对于包含字符串元素的列表, **sort( )** 会根据他们的ASCII值以升序的方式排列而通过确定reverse=True可以让他们以降序的方式排列。" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['apple', 'orange', 'peach']\n", "['peach', 'orange', 'apple']\n" ] } ], "source": [ "names = ['apple', 'orange', 'peach']\n", "names.sort()\n", "print(names)\n", "names.sort(reverse=True)\n", "print(names)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "如果要根据长度排序我们应该像图示的一样确定key=len。" ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['peach', 'apple', 'orange']\n", "['orange', 'peach', 'apple']\n" ] } ], "source": [ "names.sort(key=len)\n", "print(names)\n", "names.sort(key=len,reverse=True)\n", "print(names)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1.4 复制一个列表" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "大多数新的python程序员都会犯这个错误,即**对象的赋值和拷贝的差异**。考虑以下的例子:" ] }, { "cell_type": "code", "execution_count": 59, "metadata": { "collapsed": true }, "outputs": [], "source": [ "lista= [2,1,4,3]" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2, 1, 4, 3]\n" ] } ], "source": [ "listb = lista # 对象赋值\n", "print(listb)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "这里,我们声明了一个列表,lista = [2,1,4,3]。通过赋值将该列表复制到listb,并复制该列表。现在我们对lista执行一些随机操作。" ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2, 1, 4]\n", "[2, 1, 4, 9]\n" ] } ], "source": [ "lista.pop()\n", "print(lista)\n", "lista.append(9)\n", "print(lista)" ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2, 1, 4, 9]\n" ] } ], "source": [ "print(listb)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "虽然没有对listb执行任何操作,但它也发生了变化。这是因为您将lista、listb指向相同的内存空间。那么如何解决这个问题呢?\n", "\n", "如果您还记得,在切片中我们已经看到parentlist[a:b]从父列表返回一个起始索引a和结束索引b的列表,如果a和b没有被提及,那么默认情况下它会考虑第一个和最后一个元素。我们在这里使用相同的概念。通过这样做,我们将lista的数据作为变量分配给listb。" ] }, { "cell_type": "code", "execution_count": 63, "metadata": { "collapsed": true }, "outputs": [], "source": [ "lista = [2,1,4,3]" ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2, 1, 4, 3]\n" ] } ], "source": [ "listb = lista[:]\n", "print(listb)" ] }, { "cell_type": "code", "execution_count": 65, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2, 1, 4]\n", "[2, 1, 4, 9]\n" ] } ], "source": [ "lista.pop()\n", "print(lista)\n", "lista.append(9)\n", "print(lista)" ] }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2, 1, 4, 3]\n" ] } ], "source": [ "print(listb)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "还有其他什么方法能够拷贝一个对象到一个新的变量名字?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. 元组" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "元组与列表相似,但唯一大的区别是列表中的元素可以更改,而元组中的元素不能更改。为了更好地理解,请回忆**divmod()** 函数。" ] }, { "cell_type": "code", "execution_count": 68, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(3, 1)\n", "\n" ] }, { "ename": "TypeError", "evalue": "'tuple' object does not support item assignment", "output_type": "error", "traceback": [ "\u001b[0;31m------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0mTraceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mxyz\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtype\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mxyz\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mxyz\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m10\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: 'tuple' object does not support item assignment" ] } ], "source": [ "xyz = divmod(10,3)\n", "print(xyz)\n", "print(type(xyz))\n", "xyz[0]=10" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "这里的商必须是3余数必须是1。当10除以3时,这些值不能改变。因此,divmod以元组的形式返回这些值。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "要定义元组,将一个变量分配给paranthesis()或tuple()。" ] }, { "cell_type": "code", "execution_count": 69, "metadata": { "collapsed": true }, "outputs": [], "source": [ "tup = ()\n", "tup2 = tuple()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "如果想直接声明元组,可以在数据的末尾使用逗号。" ] }, { "cell_type": "code", "execution_count": 74, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(27,)" ] }, "execution_count": 74, "metadata": {}, "output_type": "execute_result" } ], "source": [ "27," ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "27乘以2得到54,但是乘以一个元组,数据重复两次。" ] }, { "cell_type": "code", "execution_count": 75, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(27, 27)" ] }, "execution_count": 75, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2*(27,)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "在声明元组时可以分配值。它接受一个列表作为输入并将其转换为元组,或者接受一个字符串并将其转换为元组。" ] }, { "cell_type": "code", "execution_count": 76, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(1, 2, 3)\n", "('H', 'e', 'l', 'l', 'o')\n" ] } ], "source": [ "tup3 = tuple([1,2,3])\n", "print(tup3)\n", "tup4 = tuple('Hello')\n", "print(tup4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "它遵循与列表相同的索引和切片。" ] }, { "cell_type": "code", "execution_count": 77, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "('H', 'e', 'l')\n" ] } ], "source": [ "print(tup3[1])\n", "tup5 = tup4[:3]\n", "print(tup5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.1 将一个元组映射到另一个元组" ] }, { "cell_type": "code", "execution_count": 80, "metadata": { "collapsed": true }, "outputs": [], "source": [ "(a,b,c)= ('alpha','beta','gamma')" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "alpha beta gamma\n" ] } ], "source": [ "print(a,b,c)" ] }, { "cell_type": "code", "execution_count": 81, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "('R', 'a', 'j', 'a', 't', 'h', 'K', 'u', 'm', 'a', 'r', 'M', 'P')\n" ] } ], "source": [ "d = tuple('RajathKumarMP')\n", "print(d)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2.2 元组内置函数" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**count()** 函数计算元组中存在的指定元素的数量。" ] }, { "cell_type": "code", "execution_count": 82, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 82, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d.count('a')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**index()** 函数返回指定元素的索引。如果元素大于1,则返回该指定元素的第一个元素的索引" ] }, { "cell_type": "code", "execution_count": 83, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 83, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d.index('a')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. 集合" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "集合主要用于消除序列/列表中的重复数字。它还用于执行一些标准的集合操作。\n", "\n", "set被声明为set(),它将初始化一个空集。set([sequence])也可以被执行来声明一个包含元素的集" ] }, { "cell_type": "code", "execution_count": 85, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "set1 = set()\n", "print(type(set1))" ] }, { "cell_type": "code", "execution_count": 87, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{1, 2, 3, 4}\n" ] } ], "source": [ "set0 = set([1,2,2,3,3,4])\n", "print(set0)" ] }, { "cell_type": "code", "execution_count": 88, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{1, 2, 3, 4}\n" ] } ], "source": [ "set1 = set((1,2,2,3,3,4))\n", "print(set1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "重复两次的元素2,3只会出现一次。因此在一个集合中,每个元素都是不同的。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3.1 内置函数" ] }, { "cell_type": "code", "execution_count": 89, "metadata": { "collapsed": true }, "outputs": [], "source": [ "set1 = set([1,2,3])" ] }, { "cell_type": "code", "execution_count": 90, "metadata": { "collapsed": true }, "outputs": [], "source": [ "set2 = set([2,3,4,5])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**union( )** 函数返回一个集合,该集合包含两个集合的所有元素,但是没有重复。" ] }, { "cell_type": "code", "execution_count": 91, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 2, 3, 4, 5}" ] }, "execution_count": 91, "metadata": {}, "output_type": "execute_result" } ], "source": [ "set1.union(set2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**add()** 将向集合中添加一个特定的元素。注意,新添加的元素的索引是任意的,可以放在末尾不需要的任何位置。" ] }, { "cell_type": "code", "execution_count": 92, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{1, 2, 3}\n" ] }, { "data": { "text/plain": [ "{0, 1, 2, 3}" ] }, "execution_count": 92, "metadata": {}, "output_type": "execute_result" } ], "source": [ "print(set1)\n", "set1.add(0)\n", "set1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**intersection( )** 函数输出一个集合,该集合包含两个集合中的所有元素。" ] }, { "cell_type": "code", "execution_count": 93, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{2, 3}" ] }, "execution_count": 93, "metadata": {}, "output_type": "execute_result" } ], "source": [ "set1.intersection(set2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**difference( )** 函数输出一个集合,其中包含在set1中而不在set2中的元素。" ] }, { "cell_type": "code", "execution_count": 94, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{0, 1, 2, 3}\n", "{2, 3, 4, 5}\n" ] }, { "data": { "text/plain": [ "{0, 1}" ] }, "execution_count": 94, "metadata": {}, "output_type": "execute_result" } ], "source": [ "print(set1)\n", "print(set2)\n", "set1.difference(set2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**pop( )** 是用来移除集合中的任意元素。" ] }, { "cell_type": "code", "execution_count": 115, "metadata": { "collapsed": true }, "outputs": [], "source": [ "set1=set([10, 9, 1, 2, 4])" ] }, { "cell_type": "code", "execution_count": 113, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "set()\n" ] } ], "source": [ "set1.pop()\n", "print(set1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**remove( )** 函数从集合中删除指定的元素。" ] }, { "cell_type": "code", "execution_count": 116, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1, 4, 9, 10}" ] }, "execution_count": 116, "metadata": {}, "output_type": "execute_result" } ], "source": [ "set1.remove(2)\n", "set1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**clear( )** 用于清除所有元素并将其设置为空集。" ] }, { "cell_type": "code", "execution_count": 117, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "set()" ] }, "execution_count": 117, "metadata": {}, "output_type": "execute_result" } ], "source": [ "set1.clear()\n", "set1" ] } ], "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.7.9" } }, "nbformat": 4, "nbformat_minor": 1 }