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用的是穩定的排序算法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM