List是python中的基本数据结构之一,和Java中的ArrayList有些类似,支持动态的元素的增加。list还支持不同类型的元素在一个列表中,List is an Object。
最基本的创建一个列表的方法
myList = ['a','b','c']
在python中list也是对象,所以他也有方法和属性,在ptython解释器中 使用help(list)可以查看其文档,部分开放方法如下:

在接下来的代码中,将使用这些方法:
1 1 # coding=utf-8 2 2 3 3 # Filename : list.py 4 5 # Date: 2012 11 20 5 6 6 7 7 8 8 9 # 创建一个list方式 910 heatList = \['wade','james','bosh','haslem'\] 11 tableList = list('123') #list方法接受一个iterable的参数 1012 1113 print 'Miami heat has ',len(heatList),' NBA Stars , they are:' 1214 1315 #遍历list中的元素 1416 for player in heatList: 17 print player, 18 1519 1620 #向list添加元素 1721 heatList.append('allen') #方式一:向list结尾添加 参数object 1822 print '\\nAfter allen join the team ,they are: ' 1923 print heatList 24 2025 heatList.insert(4,'lewis') #方式二:插入一个元素 参数一:index位置 参数二:object 2126 print 'After lewis join the team, they are:' 2227 print heatList 28 2329 heatList.extend(tableList) #方式三:扩展列表,参数:iterable参数 2430 print 'After extend a table list,now they are :' 2531 print heatList 32 2633 #从list删除元素 2734 heatList.remove('1') #删除方式一:参数object 如有重复元素,只会删除最靠前的 2835 print" Remove '1' ..now '1' is gone\\n",heatList 36 2937 heatList.pop() #删除方式二:pop 可选参数index删除指定位置的元素 默认为最后一个元素 3038 print "Pop the last element '3'\\n",heatList 39 3140 del heatList\[6\] #删除方式三:可以删除制定元素或者列表切片 3241 print "del '3' at the index 6\\n",heatList 42 3343 3444 #逻辑判断 3545 3646 #统计方法 count 参数:具体元素的值 3747 print 'james apears ',heatList.count('wade'),' times' 3848 3949 #in 和 not in 4050 print 'wade in list ? ',('wade' in heatList) 51 print 'wade not in list ? ',('wade' not in heatList) 52 4153 #定位 index方法:参数:具体元素的值 可选参数:切片范围 4254 print 'allen in the list ? ',heatList.index('allen') 55 #下一行代码会报错,因为allen不在前三名里 4356 #print 'allen in the fisrt 3 player ? ',heatList.index('allen',0,3) 4457 4558 #排序和反转代码 4659 print 'When the list is reversed : ' 4760 heatList.reverse() 61 print heatList 62 4863 print 'When the list is sorted: ' 4964 heatList.sort() #sort有三个默认参数 cmp=None,key=None,reverse=False 因此可以制定排序参数以后再讲 5065 print heatList 66 5167 #list 的分片\[start:end\] 分片中不包含end位置的元素 5268 print 'elements from 2nd to 3rd ' , heatList\[1:3\]
以上都是list最基本的操作,当然还包括和其他数据结构之间的转操作,注:python sort用的是稳定的排序算法
本文转自 https://www.cnblogs.com/octobershiner/archive/2012/12/04/2801611.html,如有侵权,请联系删除。
