1. 程式人生 > >Python學習-list操作

Python學習-list操作

一個 新的 刪除列 col body style HR 長度 light

Python列表(list)操作:

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

列表創建與更新:

1 #列表更新
2 list = [physics,chemistry,1997,2000]
3 print
(Value available at index 2:,list[2]) #列表的索引從0開始,依次為1 4 list[2] = 2001 #通過直接賦值可以對列表進行更新 5 print(Value available at index 2:,list[2]) 6 7 #結果: 8 #Value available at index 2: 1997 9 #Value available at index 2: 2001

列表中添加元素:

1 #使用append向列表添加元素
2 list = [physics,chemistry]
3 list.append(
wangtao) #向列表中添加元素‘wangtao‘ 4 print(list[1]) 5 print(list) 6 7 #結果 8 #chemistry 9 #[‘physics‘, ‘chemistry‘, ‘wangtao‘]

刪除列表元素:

1 #刪除列表元素
2 list = [physics, chemistry, 1997, 2000]
3 print(list)
4 del list[1]    #使用del語句可以對列表元素進行刪除
5 print(list)
6 
7 #結果
8 #[‘physics‘, ‘chemistry‘, 1997, 2000]
9
#[‘physics‘, 1997, 2000]

列表操作符:

 1 #列表操作符
 2 import operator
 3 list = [1,2,3,4,5]
 4 list2 = [2,3,4,5]
 5 print(len(list))      #len用於獲取列表的長度
 6 print(list+list2)     #‘+‘對兩個列表的元素組合成一個列表
 7 print(list*2)         #‘*‘重復列表
 8 print(3 in list)      #判斷元素是否位於列表中
 9 print(6 in list)      #判斷元素是否位於列表中
10 print(max(list))      #返回列表中元素最大值
11 print(min(list))      #返回列表中元素最小值
12 print(operator.eq(list,list2))
 1 #Python中部分operator操作
 2 operator.lt(a, b)
 3 operator.le(a, b)
 4 operator.eq(a, b)
 5 operator.ne(a, b)
 6 operator.ge(a, b)
 7 operator.gt(a, b)
 8 operator.__lt__(a, b)
 9 operator.__le__(a, b)
10 operator.__eq__(a, b)
11 operator.__ne__(a, b)
12 operator.__ge__(a, b)
13 operator.__gt__(a, b)
13 #在python 3中沒有cmp函數了,若需要比較兩個list的元素,需要調用operator模塊
14 
15 
16 #結果:
17 #5
18 #[1, 2, 3, 4, 5, 2, 3, 4, 5]
19 #[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
20 #True
21 #False
22 #5
23 #1
24 #True

列表截取:

 1 #列表截取
 2 list = [physics, chemistry, 1997, 2000]
 3 print(list[2])        #輸出索引為‘2‘的元素
 4 print(list[-3])       #輸出倒數第三個元素
 5 print(list[1:])       #從索引‘1‘開始輸出列表元素
 6 
 7 #結果:
 8 #1997
 9 #chemistry
10 #[‘chemistry‘, 1997, 2000]

其余列表操作:

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]):對原列表進行排序

Python學習-list操作