-----------
更新时间:17:36 2016-03-03 星期四10:31 2016-03-01 星期二-----------# 概述 可以容纳任何对象# 创建一个列表 只要把逗号分隔的不同的数据项使用方括号括起来即可。如下所示: list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2, 3, 4, 5 ]; list3 = ["a", "b", "c", "d"]; # 拷贝一个列表 x = [7,5,3] y = x[:] 这样y才会产生副本,不能用y=x,这样x,y 指向同一个列表,改一个地方,最终列表什 发生改变# 访问列表中的值
使用下标索引来访问列表中的值,同样你也可以使用方括号的形式截取字符,如下所示: #!/usr/bin/pythonlist1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ]; print "list1[0]: ", list1[0] print "list2[1:5]: ", list2[1:5]以上实例输出结果:
list1[0]: physics list2[1:5]: [2, 3, 4, 5]# 更新列表
你可以对列表的数据项进行修改或更新,你也可以使用append()方法来添加列表项,如下所示: #!/usr/bin/python list = ['physics', 'chemistry', 1997, 2000]; print "Value available at index 2 : " print list[2]; list[2] = 2001; print "New value available at index 2 : " print list[2]; 以上实例输出结果: Value available at index 2 : 1997 New value available at index 2 : 2001 append()追加单个元素到list尾部,若是一个列表,也当成一个整体加入 extend()将列表中每一个元素分别加到尾部 若只是单个元素 append 和 extend 没有区别 ids = [1,2,3] ids2=[3,4,5] ids.append(ids2) print ids 结果:[1, 2, 3, [3, 4, 5]] ---- ids = [1,2,3] ids2=[3,4,5] ids.extend(ids2) print ids 结果:[1, 2, 3, 3, 4, 5] insert() 将一个元素插入到列表中,但其参数有两个(如insert(1,”g”)) + 加号,将两个list相加,会返回到一个新的list对象,前面三种方法不产生 新的副本,若对象大时尽量不用 +# 删除列表元素
可以使用 del 语句来删除列表的的元素,如下实例: #!/usr/bin/python list1 = ['physics', 'chemistry', 1997, 2000]; print list1; del list1[2]; print "After deleting value at index 2 : " print list1;以上实例输出结果:
['physics', 'chemistry', 1997, 2000] After deleting value at index 2 : ['physics', 'chemistry', 2000]# Python列表脚本操作符
列表对 + 和 * 的操作符与字符串相似。+ 号用于组合列表,* 号用于重复列表。 如下所示: Python 表达式 结果 描述 len([1, 2, 3]) 3 长度 [1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] 组合 ['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] 重复 3 in [1, 2, 3] True 元素是否存在于列表中 for x in [1, 2, 3]: print x, 1 2 3 迭代# Python列表截取
Python的列表截取与字符串操作类型,如下所示: 复制代码 代码如下: L = ['spam', 'Spam', 'SPAM!']操作:
Python 表达式 结果 描述 L[2] 'SPAM!' 读取列表中第三个元素 L[-2] 'Spam' 读取列表中倒数第二个元素 L[1:] ['Spam', 'SPAM!'] 从第二个元素开始截取列表# Python列表操作的函数和方法
列表操作包含以下函数: cmp(list1, list2):比较两个列表的元素 len(list):列表元素个数 max(list):返回列表元素最大值 min(list):返回列表元素最小值 list(seq):将元组转换为列表 sorted(list) 返回排好序的列表副本,原列表不变 # 列表操作包含以下方法: list.append(obj):在列表末尾添加新的对象 list.count(obj):统计某个元素在列表中出现的次数 list.extend(seq):在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) list.index(obj):从列表中找出某个值第一个匹配项的索引位置 list.insert(index, obj):将对象插入列表 list.pop(obj=list[-1]):移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 list.remove(obj):移除列表中某个值的第一个匹配项 list.reverse():反向列表中元素 list.sort([func]):对原列表进行排序 # 解析(震撼功能) 求1到10,各数的平方数 squares = [x**2 for x in range(1,10)] 求1到100,能被3整除的数 aliquot = [n for n in range(1,100) if n%3==0] 去字符左右有空格 mybag = [' glass','apple','green leaf '] mybag = [one.strip() for one in mybag] # 列表排序 简单升序排序 x = [4, 6, 2, 1, 7, 9] x.sort() print x # [1, 2, 4, 6, 7, 9] 说明 sort()改变本身列表 -------- 产生副本排序 x =[4, 6, 2, 1, 7, 9] y = x[ : ] #产生副本 y.sort() print y #[1, 2, 4, 6, 7, 9] print x #[4, 6, 2, 1, 7, 9] 方法二: x =[4, 6, 2, 1, 7, 9] y = sorted(x) # sorted() 总是返回一个列表副本 print y #[1, 2, 4, 6, 7, 9] print x #[4, 6, 2, 1, 7, 9] --------- 自定义排序 def comp(x, y): if x < y: return 1 elif x > y: return -1 else: return 0nums = [3, 2, 8 ,0 , 1]
nums.sort(comp) print nums # 降序排序[8, 3, 2, 1, 0] nums.sort(cmp) # 调用内建函数cmp ,升序排序 print nums # 降序排序[0, 1, 2, 3, 8] ----------- 可选参数 sort方法还有两个可选参数:key和reverse x = ['mmm', 'mm', 'mm', 'm' ] x.sort(key = len) # 按长度升序 print x # ['m', 'mm', 'mm', 'mmm'] y = [3, 2, 8 ,0 , 1] y.sort(reverse = True) #降序 print y #[8, 3, 2, 1, 0] # 去重复项 # -*- coding: utf-8 -*-ids = [1,2,3,3,4,2,3,4,5,6,1]
news_ids = [] for id in ids: if id not in news_ids: news_ids.append(id) print news_ids# 判断为空
if mylist: # Do something with my list else: # The list is empty # 遍历(采用了enumerate内置函数) for i, element in enumerate(mylist): # Do something with i and element pass 同时得到key 若不要key,如下: for element in mylist: #code* 列表常规操作试验 >>> a=[] 定义一个空的列表 >>> type(a) Out[84]: list 检测a的数据类型 >>> bool(a) Out[85]: False 检测a的布尔值 >>> a=[22,33.3,'china'] >>> type(a) Out[87]: list >>> bool(a) Out[88]: True >>> a Out[89]: [22, 33.3, 'china'] 可以看到列表是以元素为单位,每个元素都可以包含不同的数据类型 >>> a[2]="chinese" >>> a Out[94]: [22, 33.3, 'chinese'] 可以看到列表是可以修改的 >>> a.append('USA') >>> a Out[97]: [22, 33.3, 'china', 'USA'] >>> a[len(a):]=['USA'] >>> a Out[107]: [22, 33.3, 'chinese', 'USA'] 列表增加元素 >>> a[2]='chinese' >>> a Out[100]: [22, 33.3, 'chinese', 'USA'] 列表修改元素 >>> a.remove('USA') >>> a Out[102]: [22, 33.3, 'chinese'] 列表删除元素,若有多个相同的值,找到最小索引那个值删除就停下来了 >>> a.pop() Out[148]: 'python' >>> a Out[149]: [33.3, 22, 'chinese', 'USA'] >>> a.pop(2) Out[150]: 'chinese' >>> a Out[151]: [33.3, 22, 'USA'] 指定弹出元素的索引,若不加,就弹出最大一个元素 列表属性序列同时支持切片操作 >>> a[:] Out[103]: [22, 33.3, 'chinese'] >>> a[2:] Out[104]: ['chinese'] >>> a[:2] Out[105]: [22, 33.3] >>> a Out[113]: [22, 33.3, 'chinese', 'USA'] >>> len(a) Out[114]: 4 得到列表的元素个数 >>> b=['php','python',99] >>> a.extend(b) >>> a Out[117]: [22, 33.3, 'chinese', 'USA', 'php', 'python', 99] 把b列表合并到a列表中,参数一定是列表对象,若是数字型会报错 >>> dd=['you','me'] >>> dd.extend('good') >>> dd Out[124]: ['you', 'me', 'g', 'o', 'o', 'd'] 先转化为列表然后再合并 >>> dd.extend(['good']) >>> dd Out[126]: ['you', 'me', 'g', 'o', 'o', 'd', 'good'] >>> a.append(22) >>> a Out[135]: [22, 33.3, 'chinese', 'USA', 'python', 22] >>> a.count(22) Out[136]: 2 统计某个值在列表中出现的次数
>>> a.index(22)
Out[137]: 0 得到22值的索引 >>> a Out[142]: [33.3, 'chinese', 'USA', 'python'] >>> a.insert(1,22) >>> a Out[144]: [33.3, 22, 'chinese', 'USA', 'python'] 在索引1前面插入22元素值 >>> a=range(1,20,2) >>> a Out[154]: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] 用range建立了数字列表 >>> dd Out[8]: ['you', 'me', 'g', 'o', 'o', 'd', 'good'] Out[159]: [0, 1, 2, 3, 4, 5, 6] >>> for i in range(len(dd)): ... print dd[i] +' is '+ str(i) ... you is 0 me is 1 g is 2 o is 3 o is 4 d is 5 good is 6 >>> for (i,item) in enumerate(dd): ... print item +' is '+str(i) ... you is 0 me is 1 g is 2 o is 3 o is 4 d is 5 good is 6 得到列表的索引列表,用了两种方法 range(len(dd)) 返回一个列表 enumerate(dd) 返回一个枚举对象 >>> a=['toby','john','kugo'] >>> a Out[3]: ['toby', 'john', 'kugo'] >>> a.sort() >>> a Out[5]: ['john', 'kugo', 'toby'] 自然排序, >>> a=['toby','john','kugo'] >>> sorted(a) Out[7]: ['john', 'kugo', 'toby'] >>> a Out[8]: ['toby', 'john', 'kugo'] 返回排好序的序列副本 >>> sorted(a,reverse=True) Out[10]: ['toby', 'kugo', 'john'] 倒序排列 字符串和列表转换 >>> str1="good,the day for over,no me \t is you" >>> str1.split() Out[20]: ['good,the', 'day', 'for', 'over,no', 'me', 'is', 'you'] 没有带参数,就任意分隔符都拿来用 >>> str1.split(',') Out[21]: ['good', 'the day for over', 'no me \t is you'] 指定逗号来分隔 >>> str1.split(',',1) Out[23]: ['good', 'the day for over,no me \t is you'] 指明只分隔一次 列表组成字符串 >>> list1 Out[28]: ['hello', 'world', 'welcome'] >>> "".join(list1) Out[29]: 'helloworldwelcome' >>> ",".join(list1) Out[30]: 'hello,world,welcome' >>> " ".join(list1) Out[31]: 'hello world welcome' * 查列表的帮助文档 dir(list) help(list.xxx) xxx具体的方法名 打开字典对象文档 print list.__doc__