1. 程式人生 > >Python list操作用法總結

Python list操作用法總結

本文例項講述了Python list操作用法。分享給大家供大家參考,具體如下:

List是python中的基本資料結構之一,和Java中的ArrayList有些類似,支援動態的元素的增加。list還支援不同型別的元素在一個列表中,List is an Object。

最基本的建立一個列表的方法

複製程式碼程式碼如下: myList = ['a','b','c']

Python list常見操作如下:

建立列表

複製程式碼程式碼如下: sample_list = ['a',1,('a','b')]

Python 列表操作

複製程式碼程式碼如下: sample_list = ['a','b',0,1,3]

得到列表中的某一個值

value_start = sample_list[0]
end_value = sample_list[-1]

刪除列表的第一個值

複製程式碼程式碼如下: del sample_list[0]

在列表中插入一個值

複製程式碼程式碼如下: sample_list[0:0] = ['sample value']

得到列表的長度

複製程式碼程式碼如下: list_length = len(sample_list)

列表遍歷

for element in sample_list:
  print(element)

Python 列表高階操作/技巧

產生一個數值遞增列表

num_inc_list = range(30)
#will return a list [0,1,2,...,29]

用某個固定值初始化列表

initial_value = 0
list_length = 5
sample_list = [ initial_value for i in range(10)]
sample_list = [initial_value]*list_length
# sample_list ==[0,0,0,0,0]

附:python內建型別

1、list:列表(即動態陣列,C++標準庫的vector,但可含不同型別的元素於一個list中)

複製程式碼程式碼如下: a = ["I","you","he","she"] #元素可為任何型別。

下標:按下標讀寫,就當作陣列處理
以0開始,有負下標的使用
0第一個元素,-1最後一個元素,
-len第一個元 素,len-1最後一個元素

取list的元素數量

len(list)   #list的長度。實際該方法是呼叫了此物件的__len__(self)方法。

建立連續的list

L = range(1,5)   #即 L=[1,2,3,4],不含最後一個元素
L = range(1, 10, 2) #即 L=[1, 3, 5, 7, 9]

list的方法

L.append(var)  #追加元素
L.insert(index,var)
L.pop(var)   #返回最後一個元素,並從list中刪除之
L.remove(var)  #刪除第一次出現的該元素
L.count(var)  #該元素在列表中出現的個數
L.index(var)  #該元素的位置,無則拋異常 
L.extend(list) #追加list,即合併list到L上
L.sort()    #排序
L.reverse()   #倒序
list 操作符:,+,*,關鍵字del
a[1:]    #片段操作符,用於子list的提取
[1,2]+[3,4] #為[1,2,3,4]。同extend()
[2]*4    #為[2,2,2,2]
del L[1]  #刪除指定下標的元素
del L[1:3] #刪除指定下標範圍的元素

list的複製

L1 = L   #L1為L的別名,用C來說就是指標地址相同,對L1操作即對L操作。函式引數就是這樣傳遞的
L1 = L[:]  #L1為L的克隆,即另一個拷貝。
複製程式碼程式碼如下: list comprehension
   [ <expr1> for k in L if <expr2> ]

2、dictionary: 字典(即C++標準庫的map)

複製程式碼程式碼如下: dict = {'ob1':'computer', 'ob2':'mouse', 'ob3':'printer'}
每一個元素是pair,包含key、value兩部分。key是Integer或string型別,value 是任意型別。

鍵是唯一的,字典只認最後一個賦的鍵值。

dictionary的方法

D.get(key, 0)    #同dict[key],多了個沒有則返回預設值,0。[]沒有則拋異常
D.has_key(key)   #有該鍵返回TRUE,否則FALSE
D.keys()      #返回字典鍵的列表
D.values()
D.items()
D.update(dict2)   #增加合併字典
D.popitem()     #得到一個pair,並從字典中刪除它。已空則拋異常
D.clear()      #清空字典,同del dict
D.copy()      #拷貝字典
D.cmp(dict1,dict2) #比較字典,(優先順序為元素個數、鍵大小、鍵值大小)
          #第一個大返回1,小返回-1,一樣返回0

dictionary的複製

dict1 = dict    #別名
dict2=dict.copy()  #克隆,即另一個拷貝。

3、tuple:元組(即常量陣列)

複製程式碼程式碼如下: tuple = ('a', 'b', 'c', 'd', 'e')
可以用list的 [],:操作符提取元素。就是不能直接修改元素。

4、string: 字串(即不能修改的字元list)

複製程式碼程式碼如下: str = "Hello My friend"
字串是一個整 體。如果你想直接修改字串的某一部分,是不可能的。但我們能夠讀出字串的某一部分。

子字串的提取

複製程式碼程式碼如下: str[:6]
字串包含 判斷操作符:in,not in
"He" in str
"she" not in str

string模組,還提供了很多方法,如

S.find(substring, [start [,end]]) #可指範圍查詢子串,返回索引值,否則返回-1
S.rfind(substring,[start [,end]]) #反向查詢
S.index(substring,[start [,end]]) #同find,只是找不到產生ValueError異常
S.rindex(substring,[start [,end]])#同上反向查詢
S.count(substring,[start [,end]]) #返回找到子串的個數
S.lowercase()
S.capitalize()   #首字母大寫
S.lower()      #轉小寫
S.upper()      #轉大寫
S.swapcase()    #大小寫互換
S.split(str, ' ')  #將string轉list,以空格切分
S.join(list, ' ')  #將list轉string,以空格連線

處理字串的內建函式

len(str)        #串長度
cmp("my friend", str)  #字串比較。第一個大,返回1
max('abcxyz')      #尋找字串中最大的字元
min('abcxyz')      #尋找字串中最小的字元

string的轉換

oat(str) #變成浮點數,float("1e-1") 結果為0.1
int(str)    #變成整型, int("12") 結果為12
int(str,base)  #變成base進位制整型數,int("11",2) 結果為2
long(str)    #變成長整型,
long(str,base) #變成base進位制長整型,

字串的格式化(注意其轉義字元,大多如C語言的,略)

str_format % (引數列表) #引數列表是以tuple的形式定義的,即不可執行中改變

複製程式碼程式碼如下: >>>print ""%s's height is %dcm" % ("My brother", 180)
          #結果顯示為 My brother's height is 180cm

list 和 tuple 的相互轉化

tuple(ls) 
list(ls)

補充:

在python中list也是物件,所以他也有方法和屬性,在ptython直譯器中 使用help(list)可以檢視其文件,部分開放方法如下:

這裡以一個例項程式碼介紹這些方法的具體用法:

# coding=utf-8
# Filename : list.py
# Date: 2012 11 20
# 建立一個list方式
heatList = ['wade','james','bosh','haslem']
tableList = list('123') #list方法接受一個iterable的引數
print 'Miami heat has ',len(heatList),' NBA Stars , they are:'
#遍歷list中的元素
for player in heatList:
  print player,
#向list新增元素
heatList.append('allen') #方式一:向list結尾新增 引數object
print '\nAfter allen join the team ,they are: '
print heatList
heatList.insert(4,'lewis') #方式二:插入一個元素 引數一:index位置 引數二:object
print 'After lewis join the team, they are:'
print heatList
heatList.extend(tableList) #方式三:擴充套件列表,引數:iterable引數
print 'After extend a table list,now they are :'
print heatList
#從list刪除元素
heatList.remove('1')  #刪除方式一:引數object 如有重複元素,只會刪除最靠前的
print" Remove '1' ..now '1' is gone\n",heatList
heatList.pop()  #刪除方式二:pop 可選引數index刪除指定位置的元素 預設為最後一個元素
print "Pop the last element '3'\n",heatList
del heatList[6] #刪除方式三:可以刪除制定元素或者列表切片
print "del '3' at the index 6\n",heatList
#邏輯判斷
#統計方法 count 引數:具體元素的值
print 'james apears ',heatList.count('wade'),' times'
#in 和 not in 
print 'wade in list ? ',('wade' in heatList)
print 'wade not in list ? ',('wade' not in heatList)
#定位 index方法:引數:具體元素的值 可選引數:切片範圍
print 'allen in the list ? ',heatList.index('allen')
#下一行程式碼會報錯,因為allen不在前三名裡
#print 'allen in the fisrt 3 player ? ',heatList.index('allen',0,3)
#排序和反轉程式碼
print 'When the list is reversed : '
heatList.reverse()
print heatList
print 'When the list is sorted: '
heatList.sort() #sort有三個預設引數 cmp=None,key=None,reverse=False 因此可以制定排序引數以後再講
print heatList
#list 的分片[start:end] 分片中不包含end位置的元素
print 'elements from 2nd to 3rd ' , heatList[1:3]

希望本文所述對大家Python程式設計有所幫助。

Python求兩個list的差集、交集與並集的方法

這篇文章主要介紹了Python求兩個list的差集、交集與並集的方法,是Python集合陣列操作中常用的技巧,需要的朋友可以參考下

本文例項講述了Python求兩個list的差集、交集與並集的方法。分享給大家供大家參考。具體如下:

list就是指兩個陣列之間的差集,交集,並集了,這個小學數學時就學過的東西,下面就以例項形式對此加以分析。

一.兩個list差集

如有下面兩個陣列:
a = [1,2,3]
b = [2,3]
想要的結果是[1]
下面記錄一下三種實現方式:
1. 正常的方式

複製程式碼程式碼如下: ret = []
for i in a:
    if i not in b:
        ret.append(i)
2. 濃縮版 複製程式碼程式碼如下: ret = [ i for i in a if i not in b ]
3. 另一版 複製程式碼程式碼如下: ret = list(set(a) ^ set(b))
個人更喜歡第三種實現方式

二. 獲取兩個list 的並集
 

複製程式碼程式碼如下: print list(set(a).union(set(b)))
三. 獲取兩個 list 的差集 複製程式碼程式碼如下: print list(set(b).difference(set(a))) # b中有而a中沒有的

Python中列表(list)操作方法彙總

本文例項彙總了Python中關於列表的常用操作方法,供大家參考借鑑。具體方法如下:

一、Python建立列表:

sample_list = ['a',1,('a','b')]

二、Python 列表操作:

假設有如下列表:

sample_list = ['a','b',0,1,3]

1.得到列表中的某一個值:

value_start = sample_list[0]
end_value = sample_list[-1]

2.刪除列表的第一個值:

del sample_list[0]

3.在列表中插入一個值:

sample_list[0:0] = ['sample value']

4.得到列表的長度:

list_length = len(sample_list)

5.列表遍歷:

for element in sample_list:
  print(element)

三、Python 列表高階操作/技巧

1.產生一個數值遞增列表:

num_inc_list = range(30)
#will return a list [0,1,2,...,29]

2.用某個固定值初始化列表:

initial_value = 0
list_length = 5
sample_list = [ initial_value for i in range(10)]
sample_list = [initial_value]*list_length
# sample_list ==[0,0,0,0,0]

讀者還可以在此基礎上繼續蒐集關於Python列表操作的其他方法,進一步鞏固及加深對Python列表操作的認識。


python list 合併連線字串的方法

python 列表合併字串,我們一般會用到字串的join方法來操作。下面通過程式碼的形式,詳細的說下list怎麼拼成字串?

比如下面一個list

複製程式碼程式碼如下:
binfo = ['lao','wang','python']

我們通過help方法得知,可以用string的join方法來解決。

下面我們通過空格來連線3個單詞:

複製程式碼程式碼如下:
content = " ".join(binfo)
print content

python中對list去重的多種方法

這篇文章主要介紹了python中對list去重的多種方法,本文去重的前提是要保證順序不變,本文給出了多種實現方法,需要的朋友可以參考下

今天遇到一個問題,在同事隨意的提示下,用了 itertools.groupby 這個函式。不過這個東西最終還是沒用上。

問題就是對一個list中的新聞id進行去重,去重之後要保證順序不變。

直觀方法

最簡單的思路就是:

複製程式碼程式碼如下:
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

這樣也可行,但是看起來不夠爽。

用set

另外一個解決方案就是用set:

複製程式碼程式碼如下:
ids = [1,4,3,3,4,2,3,4,5,6,1]
ids = list(set(ids))

這樣的結果是沒有保持原來的順序。

按照索引再次排序

最後通過這種方式解決:

複製程式碼程式碼如下:
ids = [1,4,3,3,4,2,3,4,5,6,1]
news_ids = list(set(ids))
news_ids.sort(ids.index)

使用itertools.grouby

文章一開始就提到itertools.grouby, 如果不考慮列表順序的話可用這個:

複製程式碼程式碼如下:
ids = [1,4,3,3,4,2,3,4,5,6,1]
ids.sort()
it = itertools.groupby(ids)

for k, g in it:
    print k

網友補充:用reduce

網友reatlk留言給了另外的解決方案。我補充並解釋到這裡:

複製程式碼程式碼如下:
In [5]: ids = [1,4,3,3,4,2,3,4,5,6,1]

In [6]: func = lambda x,y:x if y in x else x + [y]

In [7]: reduce(func, [[], ] + ids)
Out[7]: [1, 4, 3, 2, 5, 6]


上面是我在ipython中執行的程式碼,其中的 lambda x,y:x if y in x else x + [y] 等價於 lambda x,y: y in x and x or x+[y] 。

Python 列表(List)操作方法詳解

這篇文章主要介紹了Python中列表(List)的詳解操作方法,包含建立、訪問、更新、刪除、其它操作等,需要的朋友可以參考下

列表是Python中最基本的資料結構,列表是最常用的Python資料型別,列表的資料項不需要具有相同的型別。列表中的每個元素都分配一個數字 - 它的位置,或索引,第一個索引是0,第二個索引是1,依此類推。
Python有6個序列的內建型別,但最常見的是列表和元組。序列都可以進行的操作包括索引,切片,加,乘,檢查成員。此外,Python已經內建確定序列的長度以及確定最大和最小的元素的方法。

一、建立一個列表
只要把逗號分隔的不同的資料項使用方括號括起來即可。如下所示:

複製程式碼程式碼如下: list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];
與字串的索引一樣,列表索引從0開始。列表可以進行擷取、組合等。
二、訪問列表中的值
使用下標索引來訪問列表中的值,同樣你也可以使用方括號的形式擷取字元,如下所示:
複製程式碼程式碼如下: #!/usr/bin/python

list1 = ['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
四、刪除列表元素
可以使用 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列表操作的函式和方法
列表操作包含以下函式:
1、cmp(list1, list2):比較兩個列表的元素 
2、len(list):列表元素個數 
3、max(list):返回列表元素最大值 
4、min(list):返回列表元素最小值 
5、list(seq):將元組轉換為列表 
列表操作包含以下方法:
1、list.append(obj):在列表末尾新增新的物件
2、list.count(obj):統計某個元素在列表中出現的次數
3、list.extend(seq):在列表末尾一次性追加另一個序列中的多個值(用新列表擴充套件原來的列表)
4、list.index(obj):從列表中找出某個值第一個匹配項的索引位置
5、list.insert(index, obj):將物件插入列表
6、list.pop(obj=list[-1]):移除列表中的一個元素(預設最後一個元素),並且返回該元素的值
7、list.remove(obj):移除列表中某個值的第一個匹配項
8、list.reverse():反向列表中元素
9、list.sort([func]):對原列表進行排序