- 序列是Python中最基本的數(shù)據(jù)結(jié)構(gòu)。序列中的每個元素都分配一個數(shù)字 - 它的位置,或索引,第一個索引是0,第二個索引是1,依此類推。
- Python有6個序列的內(nèi)置類型,但最常見的是列表和元組。
- Python已經(jīng)內(nèi)置確定序列的長度以及確定最大和最小的元素的方法。
列表的創(chuàng)建及要求
- 列表是最常用的Python數(shù)據(jù)類型,創(chuàng)建一個列表,只要把逗號分隔的不同的數(shù)據(jù)項使用方括號括起來即可
- 列表的數(shù)據(jù)項不需要具有相同的類型
list1 = ['Google', 'Runoob', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
增
- 在列表末尾添加新的對象
list1 = ["張淥","何志行","Kevin","余涵睿","tiger"]
list1.append("胡老師")
print(list1)
- extend() 函數(shù)用于在列表末尾一次性追加另一個序列中的多個值(用新列表擴(kuò)展原來的列表)
aList = [123, 'xyz', 'zara', 'abc', 123];
bList = [2009, 'manni'];
aList.extend(bList)
print(aList)
- insert() 函數(shù)用于將指定對象插入列表的指定位置。必須要有位置。
aList = [123, 'xyz', 'zara', 'abc', 123];
aList.insert(0,"積分")
print(aList)
刪
- 可以使用 del 語句來刪除列表的的元素
list1 = ['Google', 'Runoob', 1997, 2000]
print(list1)
del list1[0]#在原來的列表中刪除
print(list1)
- pop() 函數(shù)用于移除列表中的一個元素(默認(rèn)最后一個元素),并且返回該元素的值
aList = [123, 'xyz', 'zara', 'abc', 123];
aList.pop(0)
print(aList)
- remove() 函數(shù)用于移除列表中某個值的第一個匹配項。
aList = [123, 'xyz', 'zara', 'abc', 123];
aList.remove(123)
print(aList)
查
- 使用下標(biāo)索引來訪問列表中的值,同樣你也可以使用方括號的形式截取字符,如下所示:
list1 = ['Google', 'Runoob', 1997, 2000]
print(list1[1])
print(list1[1:3])
print(list1[-2])#從右側(cè)開始讀取倒數(shù)第二個元素: count from the right
print(list1[1:])# 輸出從第二個元素開始后的所有元素
- 查看列表長度
list1 = ['Google', 'Runoob', 1997, 2000]
print(len(list1))
- 返回列表元素最大值\最小值( 比較數(shù)字)
list2 = [1,2,3]
print(min(list2))
print(max(list2))
- 元素是否在列表中(返回bool值)
list2 = [1,2,3]
print(1 in list2)
- 迭代(查看每一個元素)
list1 = ['Google', 'Runoob', 1997, 2000]
for a in list1:
print(a)
- count() 方法用于統(tǒng)計某個元素在列表中出現(xiàn)的次數(shù)。
list1 = ['Google', 'Runoob', 1997, 2000,2000,2000]
print(list1.count(2000))
- index() 函數(shù)用于從列表中找出某個值第一個匹配項的索引位置。
aList = [123, 'xyz', 'zara', 'abc', 123];
num = aList.index(123)
print(num)
改
- 你可以對列表的數(shù)據(jù)項進(jìn)行修改或更新
list1 = ['Google', 'Runoob', 1997, 2000]
print(list1[1])
list1[1] = "周杰倫"#把第二個元素修改了
print(list1[1])
列表對 + 和 * 的操作符與字符串相似。+ 號用于組合列表,* 號用于重復(fù)列表。
- 組合列表
list1 = ['Google', 'Runoob', 1997, 2000]
list2 = [1,2,3]
print(list1 + list2)
- 重復(fù)
list2 = [1,2,3]
print(list2*3)