【python基礎】之list列表,pythonlist列表
python提供了一個被稱為列表的資料類型,他可以儲存一個有序的元素集合。
記住:一個列表可以儲存任意大小的資料集合。列表是可變對象,有別於字串str類,str類是不可變對象。
1.建立一個列表
list1 = list() #建立一個空列表list2 = list([2,3,4]) #建立列表,包含元素2,3,4list3 = list(["red","green"]) #建立字串列表list4 = list(range(3,6)) list5 = list("abcd")
通常情況我們是將括弧省去的:
list1 = list[]list2 = list[2,3,4]
2.list的常用操作python中的字串和列表都是序列類型。一個字串是一個字串序列,而一個列表是任何元素的序列。
序列(列表)s的常用操作
| 操作 |
描述 |
| x in s |
如果元素x在序列在s中則返回true |
| x not in s |
如果元素x在序列不在s中則返回true |
| s1 + s2 |
串連兩個序列s1和s2 |
| s*n, n*s |
n個序列s的串連 |
| s[ i ] |
序列s的第 i 個元素 |
| s[ i, j ] |
序列s從下標 i 到 j-1 的片段 (列表截取) |
| len(s) |
序列s的長度,即s中的元素個數 |
| min(s) |
序列s的最小元素 |
| max(s) |
序列s的最大元素 |
| sum(s) |
序列s中所有元素之和 |
| for loop |
在for迴圈中從左至右反轉元素 |
| <,<=,>,>=,=,!= |
比較兩個序列,若真則返回true |
| random.shuffle(s) |
隨意排列序列s中的元素 |
3.下標運算子 []有列表mylist,則mylist[ index ] 中index為列表的下標,一般下標的範圍是0到len(mylist)-1. mylist[ index ]又稱為下標變數。mylist[0], mylist[1] ……分別訪問列表第0個元素,第一個元素……index還可以為負數:mylist[-1], mylist[-2]……分別訪問列表倒數第一個元素,倒數第二個元素……(為負數時index最大為-1) 4.列表截取[start:end]mylst[start:end] 截取範圍是start到end-1,構成一個列表。
>>>mylst= [0,1,2,3,4,5]>>>mylst[2,4][2, 3]
若start和end省略,則start預設為0,end預設為列表最後一個下標start和end也可以為負數,若負數為-n則換成是-n+len(mylist)即可
>>>mylist[:3][0, 1, 2]>>>mylist[2:][2, 3, 4, 5]>>>mylist[:][0, 1, 2, 3, 4, 5]>>>mylist[-4:-2][2, 3]
若start>end,則mylist發揮一個空列表
>>>mylist[3:2] #start > end ,則會報錯Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> mylist[3:2]NameError: name 'mylist' is not defined
5.列表解析列表解析由多個方括弧組成,方括弧內包含後跟一個for子句的運算式,之後是0或多個for或if子句。例如:
>>>list1 = [x for x in range(5)]>>>list1[0, 1, 2, 3, 4]>>>list2 = [0.5*x for x in list1]>>>list2[0.0, 0.5, 1.0, 1.5, 2.0]>>>list3 = [x for x in list2 if x < 1.5]>>>list3[0.0, 0.5, 1.0]
6.列表方法
常用的list方法
| append(x: object) :None |
將元素添加到列表結尾 |
| count(x: object): int |
返回元素x在列表中出現的次數 |
| extend(lst: list): None |
將列表 l 中的所有元素追加到列表中 |
| index(x: object): int |
返回x在列表中第一次出現的下標 |
| insert(index: int, x:object):None |
將元素x插入列表中指定下標處 |
| pop(i): object |
刪除給定位置的元素並返回它。參數 i 可選,若沒有指定,則刪除並返回列表中的最後一個元素 |
remove(x: object): None |
刪除列表中第一次出現的x |
| reverse(): None |
將列表中的所有元素倒序(不是排序) |
| sort(): None |
將列表中的元素升序排序(注意:是排序) |
以上代碼如下:
>>> list1 = [2, 3, 4, 1, 32, 4]>>> list1.append(19)>>> list1[2, 3, 4, 1, 32, 4, 19]>>> list1.count(4)2>>> list2 = [99, 54]>>> list2.extend(list1)>>> list2[99, 54, 2, 3, 4, 1, 32, 4, 19]>>> list2.index(4)4>>> list2.insert(1, 25) >>> list2[99, 25, 54, 2, 3, 4, 1, 32, 4, 19]>>> list2.pop() #刪除最後一個位置的元素19>>> list2[99, 25, 54, 2, 3, 4, 1, 32, 4]>>> list2.pop(2) #刪除指定位置的元素,這裡刪除下標為2的元素54>>> list2[99, 25, 2, 3, 4, 1, 32, 4]>>> list2.remove(4)>>> list2[99, 25, 2, 3, 1, 32, 4]>>> list2.reverse() #將原序列倒過來>>> list2[4, 32, 1, 3, 2, 25, 99]>>> list2.sort() #將原序列升序排序>>> list2[1, 2, 3, 4, 25, 32, 99]