1. 程式人生 > >python 列表(list)

python 列表(list)

字串可以修改嗎?

s = “123456789”

字串是不可變物件,屬於序列。可以使用索引訪問,索引可以是整數,也可以是負數,支援切片訪問等。列表也是Python內建的一種資料結構,屬於序列。

一、列表

1、列表定義

  1)列表是python的一個內建資料結構

  2)可以把列表看做一個容器

  3)該容器被隔成不同的空間,每個空間可以放任何型別“物”

  4)列表內物體只有前後的位置關係

  5)列表每個格子中的“物”是可以替換的

  6)列表是一個可變的序列

2、建立列表語法

 

1)列表定義的語法 []

       ----列表名 = [列表內容.......]

       某些情況下,列表名 和“=”可以省略,列表可以為空列表

  2)列表定義舉例

       ---[100,200,300]

      --- L=[]

      ---L=["A","B","F","g"]

      ---L =[1,"hello",2,"world"]

      ---L =[1,2,[1,2,3,4,5],"y","i"]

      ---L =[1,2,(1,2,3),9]

     ----L =[1,2,3,4,{5,6,"y","i"},8]

      ----L =[1,2,3,4,{"name":"alex","age":12},8]

3、使用list函式建立列表

   1)使用列表(list)函式建立列表    

函式 說明
list() 生產一個空列表,等同於[]
list(iterable) 用可迭代物件初始化一個列表

    2)示例       

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

L = list()
L = list("abc")
s = "suzhou"
P =list(s)
q =list([1,2,3])
print(L)
print(P)
print(q)

"""
['a', 'b', 'c']
['s', 'u', 'z', 'h', 'o', 'u']
[1, 2, 3]
Process finished with exit code 0
"""

4、列表運算

   1)+運算

      列表連結

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2,3] +["a","b","c"]
b = [9,10]
c = a+b
print(c)

"""
[1, 2, 3, 'a', 'b', 'c', 9, 10]
Process finished with exit code 0
"""

    2)+=運算

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2,3,"a","b","c"]
a+=["alex","rose"]
print(a)

"""
[1, 2, 3, 'a', 'b', 'c', 'alex', 'rose']
Process finished with exit code 0
"""

  3) *運算(複製)

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=["alex","rose"]*8
print(a)

"""
['alex', 'rose', 'alex', 'rose', 'alex', 'rose', 'alex', 'rose', 'alex', 'rose', 'alex', 'rose', 'alex', 'rose', 'alex', 'rose']
Process finished with exit code 0
"""

  4) *=運算

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=["alex","rose"]*8
print(a)

"""
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
Process finished with exit code 0
"""

 列表關係運算:返回True或者False

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2,3]
b=[1,2,3]
c=[4,5,6]
print(a!=b)
print(a==b)
print(a<c)
print(b>c)

"""
False
True
True
False

Process finished with exit code 0
"""

列表 in 和 not in 運算

如果物件在列表中返回True或者False

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2,3]
b=1
c=8
print(b in a)
print(c not in a)

"""
True
True

Process finished with exit code 0
"""

列表and,or,not 運算

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2,3]
b=[1]
c=[8]

print(a and b)
print(a or b)
print(not a)


"""
[1]
[1, 2, 3]
False

Process finished with exit code 0
"""

5、列表索引與切片訪問 

   1)l列表索引與切片訪問

      索引從0開始,列表最後一個成員的索引為列表長度-1   

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2,3,"alex",9,4]
b=a[0] #索引為負時,-1最後一個,向前類推-2就是倒數第二個
a[0]=8
c = a[-1]
print(a)
print(c)
"""
[8, 2, 3, 'alex', 9, 4]
4

Process finished with exit code 0
"""

 列表切片slice

    ----切片語法同字串【起始:結束:步長】

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2,3,"alex",9,4,5,6,7,8]
b=a[1:9:2]
print(b)
c = a[0:-3]
print(c)
f =a[-3:]
print(f)

"""
[2, 'alex', 4, 6]
[1, 2, 3, 'alex', 9, 4, 5]
[6, 7, 8]


Process finished with exit code 0
"""

 ----通過切片獲取新列表

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2,3,"alex",9,4,5,6,7,8]
b=a[1:5]
print(b)
c = a[:]  #複製列表
print(c)

"""
[2, 3, 'alex', 9]
[1, 2, 3, 'alex', 9, 4, 5, 6, 7, 8]

Process finished with exit code 0
"""

 -----列表切片賦值

切片賦值可以一次修改對個列表元素

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2,3,"alex",9,4,5,6,7,8]
a[1:3] =["hello","world"]
print(a)


"""
[1, 'hello', 'world', 'alex', 9, 4, 5, 6, 7, 8]

Process finished with exit code 0
"""

切片賦值可以增加列表元素

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2,3,"alex",9,4,5,6,7,8]
a[1:] =["hello","world","alex","rose"]
print(a)


"""
[1, 'hello', 'world', 'alex', 'rose']

Process finished with exit code 0
"""

列表切片賦值

切片賦值可以不替換任何元素情況下,為列表插入新元素

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1, 'hello', 'world', 'alex', 'rose']
a[2:2]=["a","b"]
print(a)


"""
[1, 'hello', 'a', 'b', 'world', 'alex', 'rose']

Process finished with exit code 0
"""

切片賦值可以刪除列表元素

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1, 'hello', 'world', 'alex', 'rose']
a[2:4]=[]
print(a)


"""
[1, 'hello', 'rose']

Process finished with exit code 0
"""

6、Python3中常用列表函式

    1)len函式:可以用來得到序列的長度

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1, 'hello', 'world', 'alex', 'rose']
b = len(a)
print(b)


"""
5

Process finished with exit code 0
"""

    2)max函式:可以用來得到序列最大值的元素

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2, 99,56,88]
b = max(a)
print(b)

"""
99

Process finished with exit code 0
"""

     3)min函式:可以得到列表中最小的元素

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2, 99,56,88]
b = ["a","yy","dd"]
c =["a",1,"4"]
print(min(a))
print(min(b))
print(min(c)) #報錯
"""
1
a
print(min(c))
TypeError: '<' not supported between instances of 'int' and 'str'

Process finished with exit code 0
"""

  4)sum函式

      ---可以得到列表中所有元素的和

     ---sum(列表【,起始值】)

     ---起始值可以省略,預設為0

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2,3]
b = sum(a)
print(b,type(b))
d = sum([b,10])
print(d)
"""
6 <class 'int'>
16

Process finished with exit code 0
"""

    5).index函式:得到列表中某個元素的索引(下標)

      ---L.index(value)

      ---value:要找的元素

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2,3,5,6,9,10,33,88,9]
b = a.index(9) #相同的元素只會操作第一次出現的位置
print(b)

"""
5

Process finished with exit code 0
"""

6).append函式

     ----L.append(object)

     ----object要新增的元素

     ----返回None

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2,3,5,6,9,10,33,88,9]
b = a.append("alex")
print(a)
print(b)
c = a.append([11,22])
print(a)
print(c)
"""
[1, 2, 3, 5, 6, 9, 10, 33, 88, 9, 'alex']
None
[1, 2, 3, 5, 6, 9, 10, 33, 88, 9, 'alex', [11, 22]]
None

Process finished with exit code 0
"""

7)合併列表(extend)

   向列表追加另一個列表

     ----L.extend(iterable)

     ----iterable要新增的元素(可以迭代物件)

     ----返回None

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2,3,5,6,9,10,33,88,9]
b = a.extend("alex") 
print(a)
print(b)
c = a.extend(100)
print(a)
print(c)
"""
[1, 2, 3, 5, 6, 9, 10, 33, 88, 9, 'a', 'l', 'e', 'x']
None
 c = a.extend(100)
TypeError: 'int' object is not iterable

Process finished with exit code 0
"""

    跟元組一樣,用加號(+)將兩個列表加起來即可實現合併:

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

x=list(range(1, 13, 2))

x + ['b', 'a']

print(x)
"""
[1, 3, 5, 7, 9, 11, 'b', 'a']

Process finished with exit code 0
"""

    對於已定義的列表,可以用extend方法一次性新增多個元素:

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

x=[1, 3, 5, 7, 9, 11]
x2=[3, 6, 1]
x.extend(x2)
print(x)

"""
[1, 3, 5, 7, 9, 11, 3, 6, 1]

Process finished with exit code 0
"""

需要說明的是:加號(+)執行列表的合併是非常浪費資源的,因為必須建立一個新列表並將所有物件複製過去,而用extend將元素附加到現有列表(尤其是在構建一個大列表時)就會好很多。

 因此,在進行列表合併操作時,尤其是對於大資料量的列表合併,強烈建議使用extend函式。

8).insert函式:向列表指定位置插入元素

    ---L.insert(index,object)

    ---index:位置

    ---object要插入的元素

    ---返回None

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2,3,5,6,9,10,33,88,9]
b = a.insert(2,["alex","rose"])
print(a)
print(b)
c = a.insert(5,100)
print(a)
print(c)
"""
[1, 2, ['alex', 'rose'], 3, 5, 6, 9, 10, 33, 88, 9]
None
[1, 2, ['alex', 'rose'], 3, 5, 100, 6, 9, 10, 33, 88, 9]
None

Process finished with exit code 0
"""

9).pop函式

     ---L.pop([index])

     ---刪除索引對應的元素,如果不加索引,預設刪除最後元素,同時返回移除元素

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2,3,5,6,9,10,33,88,9]
b = a.pop()
print(a)
print(b)
c = a.pop(2)
print(a)
print(c)
d = a.pop(-1)
print(a)
print(d)
"""
[1, 2, 3, 5, 6, 9, 10, 33, 88]
9
[1, 2, 5, 6, 9, 10, 33, 88]
3
[1, 2, 5, 6, 9, 10, 33]
88

Process finished with exit code 0
"""

   10).remove函式:

         ---L.remove(x)

         ---從列表中刪除第一次出現在列表中的值

         ---返回None

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2,3,5,6,9,10,"alex",33,88,9]
b = a.remove(5)
print(a)
print(b)
c = a.remove("alex")
print(a)
print(c)

"""
[1, 2, 3, 6, 9, 10, 'alex', 33, 88, 9]
None
[1, 2, 3, 6, 9, 10, 33, 88, 9]
None

Process finished with exit code 0
"""

11)del 語句刪除列表元素

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2,3,5,6,9,10,"alex",33,88,9]
b = a.remove(5)
print(a)
print(b)
c = a.remove("alex")
print(a)
print(c)

"""
[1, 2, 3, 6, 9, 10, 'alex', 33, 88, 9]
None
[1, 2, 3, 6, 9, 10, 33, 88, 9]
None

Process finished with exit code 0
"""

12).copy函式

      ---L.copy()  淺複製處解析

      ---複製此列表(只複製一層,不會複製深層物件)

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2,3,5,6,9,10,"alex",33,88,9]
b =a.copy()
print(a,id(a))
print(b,id(b))
c =a is b
print(c)
d =a
print(d,id(d))

"""
[1, 2, 3, 5, 6, 9, 10, 'alex', 33, 88, 9] 44549704
[1, 2, 3, 5, 6, 9, 10, 'alex', 33, 88, 9] 44549744
False
[1, 2, 3, 5, 6, 9, 10, 'alex', 33, 88, 9] 44549704
Process finished with exit code 0
"""

13).reverse

       ---列表的反轉,只反轉排列順序,列表的值是不會改變的

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2,3,5,6,9,10,"alex",33,88,9]
print("反轉前的資料===》",a)
b =a.reverse()
print("反轉後的資料===》",a)
print(b)


"""
反轉前的資料===》 [1, 2, 3, 5, 6, 9, 10, 'alex', 33, 88, 9]
反轉後的資料===》 [9, 88, 33, 'alex', 10, 9, 6, 5, 3, 2, 1]
None
Process finished with exit code 0
"""

14).sort

     --Lsort(reverse = False)

     ---將列表的順序按值得小到大的順序進行排列

 列表的sort方法可以實現就地排序(無需建立新物件,字串按首字母進行排序):

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,72,3,45,6,9,10,33,88,9]
print("排序前的資料===》",a)
b =a.sort()
print("排序後的資料===》",a)
print(b)
s=['a','ab','3e','z']
print("排序前的資料===》",s)
g=s.sort()
print("排序後的資料===》",s)


"""
排序前的資料===》 [1, 72, 3, 45, 6, 9, 10, 33, 88, 9]
排序後的資料===》 [1, 3, 6, 9, 9, 10, 33, 45, 72, 88]
None
排序前的資料===》 ['a', 'ab', '3e', 'z']
排序後的資料===》 ['3e', 'a', 'ab', 'z']
Process finished with exit code 0
"""


 

sort有幾個很好用的選項,一個是次要排序鍵,即一個能夠產生可用於排序的值的函式。如可以通過長度對一組字串進行排序:

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

b=['a','nl','drz','mowgt','aa']
b.sort(key=len)
print(b)


"""
['a', 'nl', 'aa', 'drz', 'mowgt']
Process finished with exit code 0
"""

 再比如是否進行降序排列,如下面通過對首字母進行降序排列的示例:

__author__ = 'Administrator'

# -*- coding:utf-8 -*-
b=['a','nl','drz','mowgt','aa']
b.sort(key= lambda x:x[0], reverse=True)
print(b)


"""
['nl', 'mowgt', 'drz', 'a', 'aa']
Process finished with exit code 0
"""


 

15).clean:清空列表

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2,3,5,6,9,10,"alex",33,88,9]
print("清空前的資料===》",a)
b =a.clear()
print("清空後的資料===》",a)
print(b)


"""
清空前的資料===》 [1, 2, 3, 5, 6, 9, 10, 'alex', 33, 88, 9]
清空後的資料===》 []
None
Process finished with exit code 0
"""

7、列表的遍歷

    1)使用while迴圈

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2,3,5,6,9,10,"alex",33,88,9]
i=0
while i<len(a):
    print(a[i])
    i+=1


"""
1
2
3
5
6
9
10
alex
33
88
9
Process finished with exit code 0
"""

   2)使用for循壞

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2,3,5,6,9,10,"alex",33,88,9]
for i in a:
    print(i)


"""
1
2
3
5
6
9
10
alex
33
88
9
Process finished with exit code 0
"""

8、列表複製

  淺複製只複製一層

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a=[1,2,3,5,6,9,10,"alex",33,88,9]
b=a
print(b)
b[0]="rose"
print(b)
print(a)
print(a is b)


"""
[1, 2, 3, 5, 6, 9, 10, 'alex', 33, 88, 9]
['rose', 2, 3, 5, 6, 9, 10, 'alex', 33, 88, 9]
['rose', 2, 3, 5, 6, 9, 10, 'alex', 33, 88, 9]
True

Process finished with exit code 0
"""

深拷貝需要使用copy模組

---全部複製

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

import copy

a=[1,2,3,5,[6,9,10],"alex",33,88,9]
b = copy.deepcopy(a)
print(a,id(a))
print(b,id(b))
print(a is b)
b[4][0]=40
print(b)



"""
[1, 2, 3, 5, [6, 9, 10], 'alex', 33, 88, 9] 47178256
[1, 2, 3, 5, [6, 9, 10], 'alex', 33, 88, 9] 47179016
False
[1, 2, 3, 5, [6, 9, 10], 'alex', 33, 88, 9]
[1, 2, 3, 5, [40, 9, 10], 'alex', 33, 88, 9]

Process finished with exit code 0
"""

9、列表推導式語法

列表推導式是用可迭代物件依次生成列表內元素的方式

語法:

【表示式for 變數 in 可迭代物件】

【表示式 for 變數 in 可迭代物件 if 條件語句】

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

y = [ x**2 for x in range(1,10)]
print(y)
z =[x**2 for x in range(1,10) if x%2==1]
print(z)



"""
[1, 4, 9, 16, 25, 36, 49, 64, 81]
[1, 9, 25, 49, 81]

Process finished with exit code 0
"""

列表推導式巢狀語法

【表示式1 for 變數1 in 可迭代物件1 if 條件語句1 for 變數2 in 可迭代物件3 if 條件語句2】

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

y = [x*y for x in [2,3,5] for y in [7,11,13]]
print(y)


"""
[14, 22, 26, 21, 33, 39, 35, 55, 65]

Process finished with exit code 0
"""

10、列表與字串

       字串拆分與拼接

        ----S.split (sep = None,maxsplit = -1)    --->list of string

        -----S.join(iterable)   ---->str

__author__ = 'Administrator'

# -*- coding:utf-8 -*-

a="beijing is captical !"
b =a.split(" ")
print(b)
c = a.split(maxsplit=1)
d = a.split(maxsplit=2)
f = a.split(maxsplit=3)
print(c)
print(d)
print(f)

print("-------join--------")
g="/"
print(g)
h = g.join(["C:","progrom file","python"])
print(h)

"""
['beijing', 'is', 'captical', '!']
['beijing', 'is captical !']
['beijing', 'is', 'captical !']
['beijing', 'is', 'captical', '!']
-------join--------
/
C:/progrom file/python


Process finished with exit code 0
"""

11、字串與列表比較

       ---列表 和字串都是序列,元素之間有先後關係

       ---字串中的每個元素只能儲存字元,而列表可以儲存任意型別

       ---字串是不可變的序列,而列表是可以改變的序列