前面簡單介紹了Python字符串基本操作,這里再來簡單講述一下Python列表相關操作
>>> dir(list) #查看列表list相關的屬性和方法['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']>>> lst = [] #定義一個空列表>>> type(lst) #判斷列表類型<class 'list'>>>> bool(lst) #bool()函數(shù)可判斷對象真假,這里判斷空列表lst為假False>>> print(lst)[]>>> a = ['1','False','jb51']>>> type(a)<class 'list'>>>> bool(a)True>>> print(a)['1', 'False', 'jb51']>>>
append() | 在列表末尾追加元素 |
count() | 統(tǒng)計元素出現(xiàn)次數(shù) |
extend() | 用一個列表追加擴充另一個列表 |
index() | 檢索元素在列表中第一次出現(xiàn)的位置 |
insert() | 在指定位置追加元素 |
pop() | 刪除最后一個元素(也可指定刪除的元素位置) |
remove() | 刪除指定元素 |
reverse() | 將列表元素順序反轉 |
sort() | 對列表排序 |
len() | 計算列表元素個數(shù) |
>>> list1 = [1,2,3,4,5,6]>>> list1.append(1)>>> list1.count(1)2>>> list2 = ['Tom',7]>>> list1.extend(list2) # 列表list1后追加列表list2>>> list1[1, 2, 3, 4, 5, 6, 1, 'Tom', 7]>>> list1.extend(['haha',8]) # 可以直接在extend函數(shù)的參數(shù)中使用列表>>> list1[1, 2, 3, 4, 5, 6, 1, 'Tom', 7, 'haha', 8]>>> list1.insert(2,'huhu') # 使用insert函數(shù)在序號2處添加元素'huhu'>>> list1[1, 2, 'huhu', 3, 4, 5, 6, 1, 'Tom', 7, 'haha', 8]>>> list1.pop() # pop()方法取出棧尾元素8>>> tmp = list1.pop() #可以將棧尾元素賦值便于使用>>> tmp'haha'>>> list1.remove('huhu') #使用remove()函數(shù)刪除指定元素'huhu'>>> list1[1, 2, 3, 4, 5, 6, 1, 'Tom', 7]>>> list1.reverse()>>> list1[7, 'Tom', 1, 6, 5, 4, 3, 2, 1]>>> list1.sort() #這里使用sort()排序,但是包含字符串類型與整數(shù)類型,會報錯!Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> list1.sort()TypeError: '<' not supported between instances of 'str' and 'int'>>> list1.remove('Tom')>>> list1.sort()>>> list1[1, 1, 2, 3, 4, 5, 6, 7]>>> list1 = list(set(list1)) # 列表list去重(先使用set轉換為不重復集合,再使用list類型轉換回列表)>>> list1[1, 2, 3, 4, 5, 6, 7]>>> l = len(list1) #使用len()方法求列表長度>>> l7>>> list1.index(5) # index()獲取元素出現(xiàn)的位置4
新聞熱點
疑難解答