Python中的基本list操作

List是python中的基本数据结构之一,和Java中的ArrayList有些类似,支持动态的元素的增加。list还支持不同类型的元素在一个列表中,List is an Object。

 

最基本的创建一个列表的方法

myList = ['a','b','c']

 

在python中list也是对象,所以他也有方法和属性,在ptython解释器中 使用help(list)可以查看其文档,部分开放方法如下:

在接下来的代码中,将使用这些方法:

 1 # coding=utf-8
 2 
 3 # Filename : list.py
 5 # Date: 2012 11 20
 6 
 7 
 8 
 9 # 创建一个list方式
10 heatList = ['wade','james','bosh','haslem']
11 tableList = list('123')  #list方法接受一个iterable的参数
12 
13 print 'Miami heat has ',len(heatList),' NBA Stars , they are:'
14 
15 #遍历list中的元素
16 for player in heatList:
17     print player,
18 
19 
20 #向list添加元素
21 heatList.append('allen') #方式一:向list结尾添加 参数object
22 print '\nAfter allen join the team ,they are: '
23 print heatList
24 
25 heatList.insert(4,'lewis') #方式二:插入一个元素 参数一:index位置 参数二:object
26 print 'After lewis join the team, they are:'
27 print heatList
28 
29 heatList.extend(tableList)  #方式三:扩展列表,参数:iterable参数
30 print 'After extend a table list,now they are :'
31 print heatList
32 
33 #从list删除元素
34 heatList.remove('1')   #删除方式一:参数object 如有重复元素,只会删除最靠前的
35 print" Remove '1' ..now '1' is gone\n",heatList
36 
37 heatList.pop()   #删除方式二:pop 可选参数index删除指定位置的元素 默认为最后一个元素
38 print "Pop the last element '3'\n",heatList
39 
40 del heatList[6] #删除方式三:可以删除制定元素或者列表切片
41 print "del '3' at the index 6\n",heatList
42 
43 
44 #逻辑判断
45 
46 #统计方法 count 参数:具体元素的值
47 print 'james apears ',heatList.count('wade'),' times'
48 
49 #in 和 not in 
50 print 'wade in list ? ',('wade' in heatList)
51 print 'wade not in list ? ',('wade' not in heatList)
52 
53 #定位 index方法:参数:具体元素的值 可选参数:切片范围
54 print 'allen in the list ? ',heatList.index('allen')
55 #下一行代码会报错,因为allen不在前三名里
56 #print 'allen in the fisrt 3 player ? ',heatList.index('allen',0,3)
57 
58 #排序和反转代码
59 print 'When the list is reversed : '
60 heatList.reverse()
61 print heatList
62 
63 print 'When the list is sorted: '
64 heatList.sort() #sort有三个默认参数 cmp=None,key=None,reverse=False 因此可以制定排序参数以后再讲
65 print heatList
66 
67 #list 的分片[start:end] 分片中不包含end位置的元素
68 print 'elements from 2nd to 3rd ' , heatList[1:3]

 

以上都是list最基本的操作,当然还包括和其他数据结构之间的转操作,注:python sort用的是稳定的排序算法

posted @ 2012-12-04 16:40  leeon  阅读(34218)  评论(0编辑  收藏  举报