Python入門教程3. 列表基本操作【定義、運算、常用函數】 原創(chuàng)
原創(chuàng) 更新時間:2018年10月30日 23:53:25 原創(chuàng) 作者:chenge
這篇文章主要介紹了Python列表基本操作,結合實例形式總結分析了Python針對列表的基本定義、判斷、運算及各種常用函數與相關使用技巧,需要的朋友可以參考下
前面簡單介紹了Python字符串基本操作,這里再來簡單講述一下Python列表相關操作
1. 基本定義與判斷
>>> 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()函數可判斷對象真假,這里判斷空列表lst為假 False >>> print(lst) [] >>> a = ['1','False','jb51'] >>> type(a) <class 'list'> >>> bool(a) True >>> print(a) ['1', 'False', 'jb51'] >>>
2. 列表常用操作函數:
append() |
在列表末尾追加元素 |
count() |
統(tǒng)計元素出現(xiàn)次數 |
extend() |
用一個列表追加擴充另一個列表 |
index() |
檢索元素在列表中第一次出現(xiàn)的位置 |
insert() |
在指定位置追加元素 |
pop() |
刪除最后一個元素(也可指定刪除的元素位置) |
remove() |
刪除指定元素 |
reverse() |
將列表元素順序反轉 |
sort() |
對列表排序 |
len() |
計算列表元素個數 |
>>> 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函數的參數中使用列表
>>> list1
[1, 2, 3, 4, 5, 6, 1, 'Tom', 7, 'haha', 8]
>>> list1.insert(2,'huhu') # 使用insert函數在序號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()函數刪除指定元素'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()排序,但是包含字符串類型與整數類型,會報錯!
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()方法求列表長度
>>> l
7
>>> list1.index(5) # index()獲取元素出現(xiàn)的位置
4
簡單入門教程~
基本一看就懂~O(∩_∩)O~
未完待續(xù)~~歡迎討論!!

