python list_Python中的基本list操作
1 #coding=utf-8
2
3 #Filename : list.py
5 #Date: 2012 11 20
6
7
8
9 #創(chuàng)建一個(gè)list方式
10 heatList = ['wade','james','bosh','haslem']11 tableList = list('123') #list方法接受一個(gè)iterable的參數(shù)
12
13 print 'Miami heat has',len(heatList),'NBA Stars , they are:'
14
15 #遍歷list中的元素
16 for player inheatList:17 printplayer,18
19
20 #向list添加元素
21 heatList.append('allen') #方式一:向list結(jié)尾添加 參數(shù)object
22 print '\nAfter allen join the team ,they are:'
23 printheatList24
25 heatList.insert(4,'lewis') #方式二:插入一個(gè)元素 參數(shù)一:index位置 參數(shù)二:object
26 print 'After lewis join the team, they are:'
27 printheatList28
29 heatList.extend(tableList) #方式三:擴(kuò)展列表,參數(shù):iterable參數(shù)
30 print 'After extend a table list,now they are :'
31 printheatList32
33 #從list刪除元素
34 heatList.remove('1') #刪除方式一:參數(shù)object 如有重復(fù)元素,只會(huì)刪除最靠前的
35 print"Remove '1' ..now '1' is gone\n",heatList36
37 heatList.pop() #刪除方式二:pop 可選參數(shù)index刪除指定位置的元素 默認(rèn)為最后一個(gè)元素
38 print "Pop the last element '3'\n",heatList39
40 del heatList[6] #刪除方式三:可以刪除制定元素或者列表切片
41 print "del '3' at the index 6\n",heatList42
43
44 #邏輯判斷
45
46 #統(tǒng)計(jì)方法 count 參數(shù):具體元素的值
47 print 'james apears',heatList.count('wade'),'times'
48
49 #in 和 not in
50 print 'wade in list ?',('wade' inheatList)51 print 'wade not in list ?',('wade' not inheatList)52
53 #定位 index方法:參數(shù):具體元素的值 可選參數(shù):切片范圍
54 print 'allen in the list ?',heatList.index('allen')55 #下一行代碼會(huì)報(bào)錯(cuò),因?yàn)閍llen不在前三名里
56 #print 'allen in the fisrt 3 player ? ',heatList.index('allen',0,3)
57
58 #排序和反轉(zhuǎn)代碼
59 print 'When the list is reversed :'
60 heatList.reverse()61 printheatList62
63 print 'When the list is sorted:'
64 heatList.sort() #sort有三個(gè)默認(rèn)參數(shù) cmp=None,key=None,reverse=False 因此可以制定排序參數(shù)以后再講
65 printheatList66
67 #list 的分片[start:end] 分片中不包含end位置的元素
68 print 'elements from 2nd to 3rd' , heatList[1:3]
總結(jié)
以上是生活随笔為你收集整理的python list_Python中的基本list操作的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 父爱动画代码python_pygame用
- 下一篇: activity 启动模式_Intent