|
| 1 | +#列表(2) |
| 2 | + |
| 3 | +上一节中已经谈到,list是python的苦力,那么它都有哪些函数呢?或者它或者对它能做什么呢?在交互模式下这么操作,就看到有关它的函数了。 |
| 4 | + |
| 5 | + >>> dir(list) |
| 6 | + ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] |
| 7 | + |
| 8 | +上面的结果中,以双下划线开始和结尾的暂时不管,如`__add__`(以后会管的)。就剩下以下几个了: |
| 9 | + |
| 10 | +>'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort' |
| 11 | +
|
| 12 | +下面注意对这些函数进行说明和演示。这都是在编程实践中常常要用到的。 |
| 13 | + |
| 14 | +##list函数 |
| 15 | + |
| 16 | +###append和extend |
| 17 | + |
| 18 | +[《列表(1)》](./111.md)中,对list的基本操作提到了list.append(x),也就是将某个元素x 追加到已知的一个list后边。 |
| 19 | + |
| 20 | +除了将元素追加到list中,还能够将两个list合并,或者说将一个list追加到另外一个list中。按照前文的惯例,还是首先看[官方文档](https://docs.python.org/2/tutorial/datastructures.html)中的描述: |
| 21 | + |
| 22 | +>list.extend(L) |
| 23 | +
|
| 24 | +> Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L. |
| 25 | +
|
| 26 | +**向所有正在学习本内容的朋友提供一个成为优秀程序员的必备:看官方文档,是必须的。** |
| 27 | + |
| 28 | +官方文档的这句话翻译过来: |
| 29 | + |
| 30 | +>通过将所有元素追加到已知list来扩充它,相当于a[len(a):]= L |
| 31 | +
|
| 32 | +英语太烂,翻译太差。直接看例子,更明白 |
| 33 | + |
| 34 | + >>> la |
| 35 | + [1, 2, 3] |
| 36 | + >>> lb |
| 37 | + ['qiwsir', 'python'] |
| 38 | + >>> la.extend(lb) |
| 39 | + >>> la |
| 40 | + [1, 2, 3, 'qiwsir', 'python'] |
| 41 | + >>> lb |
| 42 | + ['qiwsir', 'python'] |
| 43 | + |
| 44 | +上面的例子,显示了如何将两个list,一个是la,另外一个lb,将lb追加到la的后面,也就是把lb中的所有元素加入到la中,即让la扩容。 |
| 45 | + |
| 46 | +学程序一定要有好奇心,我在交互环境中,经常实验一下自己的想法,有时候是比较愚蠢的想法。 |
| 47 | + |
| 48 | + >>> la = [1,2,3] |
| 49 | + >>> b = "abc" |
| 50 | + >>> la.extend(b) |
| 51 | + >>> la |
| 52 | + [1, 2, 3, 'a', 'b', 'c'] |
| 53 | + >>> c = 5 |
| 54 | + >>> la.extend(c) |
| 55 | + Traceback (most recent call last): |
| 56 | + File "<stdin>", line 1, in <module> |
| 57 | + TypeError: 'int' object is not iterable |
| 58 | + |
| 59 | +从上面的实验中,看官能够有什么心得?原来,如果extend(str)的时候,str被以字符为单位拆开,然后追加到la里面。 |
| 60 | + |
| 61 | +如果extend的对象是数值型,则报错。 |
| 62 | + |
| 63 | +所以,extend的对象是一个list,如果是str,则python会先把它按照字符为单位转化为list再追加到已知list。 |
| 64 | + |
| 65 | +不过,别忘记了前面官方文档的后半句话,它的意思是: |
| 66 | + |
| 67 | + >>> la |
| 68 | + [1, 2, 3, 'a', 'b', 'c'] |
| 69 | + >>> lb |
| 70 | + ['qiwsir', 'python'] |
| 71 | + >>> la[len(la):]=lb |
| 72 | + >>> la |
| 73 | + [1, 2, 3, 'a', 'b', 'c', 'qiwsir', 'python'] |
| 74 | + |
| 75 | +list.extend(L) 等效于 list[len(list):] = L,L是待并入的list |
| 76 | + |
| 77 | +联想到到[上一讲](./111.md)中的一个list函数list.append(),有类似之处。 |
| 78 | + |
| 79 | +>extend(...) |
| 80 | +> L.extend(iterable) -- extend list by appending elements from the iterable |
| 81 | +
|
| 82 | +上面是在交互模式中输入`help(list.extend)`后得到的说明。这是非常重要而且简单的获得文档帮助的方法。 |
| 83 | + |
| 84 | +从上面内容可知,extend函数也是将另外的元素增加到一个已知列表中,其元素必须是iterable,什么是iterable?这个从现在开始,后面会经常遇到,所以是要搞搞清楚的。 |
| 85 | + |
| 86 | +>iterable,中文含义是“可迭代的”。在python中,还有一个词,就是iterator,这个叫做“迭代器”。这两者有着区别和联系。不过,这里暂且不说那么多,说多了就容易糊涂,我也糊涂了。 |
| 87 | +
|
| 88 | +为了解释iterable(可迭代的),又引入了一个词“迭代”,什么是迭代呢? |
| 89 | + |
| 90 | +>尽管我们很多文档是用英文写的,但是,如果你能充分利用汉语来理解某些名词,是非常有帮助的。因为在汉语中,不仅仅表音,而且能从词语组合中体会到该术语的含义。比如“激光”,这是汉语。英语是从"light amplification by stimulated emission of radiation"化出来的"laser",它是一个造出来的词。因为此前人们不知道那种条件下发出来的是什么。但是汉语不然,反正用一个“光”就可以概括了,只不过这个“光”不是传统概念中的“光”,而是由于“受激”辐射得到的光,故名“激光”。是不是汉语很牛叉? |
| 91 | +
|
| 92 | +>“迭”在汉语中的意思是“屡次,反复”。如:高潮迭起。那么跟“代”组合,就可以理解为“反复‘代’”,是不是有点“子子孙孙”的意思了?“结婚-生子-子成长-结婚-生子-子成长-...”,你是不是也在这个“迭代”的过程中呢? |
| 93 | +
|
| 94 | +>给个稍微严格的定义,来自维基百科。“迭代是重复反馈过程的活动,其目的通常是为了接近并到达所需的目标或结果。” |
| 95 | +
|
| 96 | +某些类型的对象是“可迭代”(iterable)的,这类数据类型有共同的特点。如何判断一个对象是不是可迭代的?下面演示一种方法。事实上还有别的方式。 |
| 97 | + |
| 98 | + >>> astr = "python" |
| 99 | + >>> hasattr(astr,'__iter__') |
| 100 | + False |
| 101 | + |
| 102 | +这里用内建函数`hasattr()`判断一个字符串是否是可迭代的,返回了False。用同样的方式可以判断: |
| 103 | + |
| 104 | + >>> alst = [1,2] |
| 105 | + >>> hasattr(alst,'__iter__') |
| 106 | + True |
| 107 | + >>> hasattr(3, '__iter__') |
| 108 | + False |
| 109 | + |
| 110 | +`hasattr()`的判断本质就是看那个类型中是否有`__iter__`函数。看官可以用`dir()`找一找,在数字、字符串、列表中,谁有`__iter__`。同样还可找一找dict,tuple两种类型对象是否含有这个方法。 |
| 111 | + |
| 112 | +以上穿插了一个新的概念“iterable”(可迭代的),现在回到extend上。这个函数需要的参数就是iterable类型的对象。 |
| 113 | + |
| 114 | + >>> new = [1,2,3] |
| 115 | + >>> lst = ['python','qiwsir'] |
| 116 | + >>> lst.extend(new) |
| 117 | + >>> lst |
| 118 | + ['python', 'qiwsir', 1, 2, 3] |
| 119 | + >>> new |
| 120 | + [1, 2, 3] |
| 121 | + |
| 122 | +通过extend函数,将[1,2,3]中的每个元素都拿出来,然后塞到lst里面,从而得到了一个跟原来的对象元素不一样的列表,后面的比原来的多了三个元素。上面说的有点啰嗦,只不过是为了把过程完整表达出来。 |
| 123 | + |
| 124 | +还要关注一下,从上面的演示中可以看出,lst经过extend函数操作之后,变成了一个貌似“新”的列表。这句话好像有点别扭,“貌似新”的,之所以这么说,是因为对“新的”可能有不同的理解。不放深挖一下。 |
| 125 | + |
| 126 | + >>> new = [1,2,3] |
| 127 | + >>> id(new) |
| 128 | + 3072383244L |
| 129 | + |
| 130 | + >>> lst = ['python', 'qiwsir'] |
| 131 | + >>> id(lst) |
| 132 | + 3069501420L |
| 133 | + |
| 134 | +用`id()`能够看到两个列表分别在内存中的“窝”的编号。 |
| 135 | + |
| 136 | + >>> lst.extend(new) |
| 137 | + >>> lst |
| 138 | + ['python', 'qiwsir', 1, 2, 3] |
| 139 | + >>> id(lst) |
| 140 | + 3069501420L |
| 141 | + |
| 142 | +看官注意到没有,虽然lst经过`extend()`方法之后,比原来扩容了,但是,并没有离开原来的“窝”,也就是在内存中,还是“旧”的,只不过里面的内容增多了。相当于两口之家,经过一番云雨之后,又增加了一个小宝宝,那么这个家是“新”的还是“旧”的呢?角度不同或许说法不一了。 |
| 143 | + |
| 144 | +这就是列表的一个**重要特征:列表是可以修改的。这种修改,不是复制一个新的,而是在原地进行修改。** |
| 145 | + |
| 146 | +其实,`append()`对列表的操作也是如此,不妨用同样的方式看看。 |
| 147 | + |
| 148 | +**说明:**虽然这里的lst内容和上面的一样,但是,我从新在shell中输入,所以id会变化。也就是内存分配的“窝”的编号变了。 |
| 149 | + |
| 150 | + >>> lst = ['python','qiwsir'] |
| 151 | + >>> id(lst) |
| 152 | + 3069501388L |
| 153 | + >>> lst.append(new) |
| 154 | + >>> lst |
| 155 | + ['python', 'qiwsir', [1, 2, 3]] |
| 156 | + >>> id(lst) |
| 157 | + 3069501388L |
| 158 | + |
| 159 | +显然,`append()`也是原地修改列表。 |
| 160 | + |
| 161 | +如果,对于`extend()`,提供的不是iterable类型对象,会如何呢? |
| 162 | + |
| 163 | + >>> lst.extend("itdiffer") |
| 164 | + >>> lst |
| 165 | + ['python', 'qiwsir', 'i', 't', 'd', 'i', 'f', 'f', 'e', 'r'] |
| 166 | + |
| 167 | +它把一个字符串"itdiffer"转化为['i', 't', 'd', 'i', 'f', 'f', 'e', 'r'],然后将这个列表作为参数,提供给extend,并将列表中的元素塞入原来的列表中。 |
| 168 | + |
| 169 | + >>> num_lst = [1,2,3] |
| 170 | + >>> num_lst.extend(8) |
| 171 | + Traceback (most recent call last): |
| 172 | + File "<stdin>", line 1, in <module> |
| 173 | + TypeError: 'int' object is not iterable |
| 174 | + |
| 175 | +这就报错了。错误提示中告诉我们,那个数字8,是int类型的对象,不是iterable的。 |
| 176 | + |
| 177 | +这里讲述的两个让列表扩容的函数`append()`和`extend()`。从上面的演示中,可以看到他们有相同的地方: |
| 178 | + |
| 179 | +- 都是原地修改列表 |
| 180 | +- 既然是原地修改,就不返回值(这点特别要注意,没有返回值,就不能赋值给某个变量) |
| 181 | + |
| 182 | + >>> one = ["good","good","study"] |
| 183 | + >>> another = one.extend(["day","day","up"]) #对于没有提供返回值的函数,如果要这样,结果是: |
| 184 | + >>> another #这样的,什么也没有得到。 |
| 185 | + >>> one |
| 186 | + ['good', 'good', 'study', 'day', 'day', 'up'] |
| 187 | + |
| 188 | +那么两者有什么不一样呢?看下面例子: |
| 189 | + |
| 190 | + >>> lst = [1,2,3] |
| 191 | + >>> lst.append(["qiwsir","github"]) |
| 192 | + >>> lst |
| 193 | + [1, 2, 3, ['qiwsir', 'github']] #append的结果 |
| 194 | + >>> len(lst) |
| 195 | + 4 |
| 196 | + |
| 197 | + >>> lst2 = [1,2,3] |
| 198 | + >>> lst2.extend(["qiwsir","github"]) |
| 199 | + >>> lst2 |
| 200 | + [1, 2, 3, 'qiwsir', 'github'] #extend的结果 |
| 201 | + >>> len(lst2) |
| 202 | + 5 |
| 203 | + |
| 204 | +append是整建制地追加,extend是个体化扩编。 |
| 205 | + |
| 206 | +###count |
| 207 | + |
| 208 | +上面的len(L),可得到list的长度,也就是list中有多少个元素。python的list还有一个函数,就是数一数某个元素在该list中出现多少次,也就是某个元素有多少个。官方文档是这么说的: |
| 209 | + |
| 210 | +>list.count(x) |
| 211 | +
|
| 212 | +>Return the number of times x appears in the list. |
| 213 | +
|
| 214 | +一定要不断实验,才能理解文档中精炼的表达。 |
| 215 | + |
| 216 | + >>> la = [1,2,1,1,3] |
| 217 | + >>> la.count(1) |
| 218 | + 3 |
| 219 | + >>> la.append('a') |
| 220 | + >>> la.append('a') |
| 221 | + >>> la |
| 222 | + [1, 2, 1, 1, 3, 'a', 'a'] |
| 223 | + >>> la.count('a') |
| 224 | + 2 |
| 225 | + >>> la.count(2) |
| 226 | + 1 |
| 227 | + >>> la.count(5) #NOTE:la中没有5,但是如果用这种方法找,不报错,返回的是数字0 |
| 228 | + 0 |
| 229 | + |
| 230 | +###index |
| 231 | + |
| 232 | +[《列表(1)》](./111.md)中已经提到,这里不赘述,但是为了完整,也占个位置吧。 |
| 233 | + |
| 234 | + >>> la |
| 235 | + [1, 2, 3, 'a', 'b', 'c', 'qiwsir', 'python'] |
| 236 | + >>> la.index(3) |
| 237 | + 2 |
| 238 | + >>> la.index('qi') #如果不存在,就报错 |
| 239 | + Traceback (most recent call last): |
| 240 | + File "<stdin>", line 1, in <module> |
| 241 | + ValueError: 'qi' is not in list |
| 242 | + >>> la.index('qiwsir') |
| 243 | + 6 |
| 244 | + |
| 245 | +list.index(x),x是list中的一个元素,这样就能够检索到该元素在list中的位置了。这才是真正的索引,注意那个英文单词index。 |
| 246 | + |
| 247 | +依然是上一条官方解释: |
| 248 | + |
| 249 | +>list.index(x) |
| 250 | +
|
| 251 | +>Return the index in the list of the first item whose value is x. It is an error if there is no such item. |
| 252 | +
|
| 253 | +是不是说的非常清楚明白了? |
| 254 | + |
| 255 | +------ |
| 256 | + |
| 257 | +[总目录](./index.md) | [上节:列表(1)](./111.md) | [下节:列表(3)](./113.md) |
| 258 | + |
| 259 | +如果你认为有必要打赏我,请通过支付宝:**qiwsir@126.com**,不胜感激。 |
0 commit comments