国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

第二章-列表和元組——python基礎教程(第二版)筆記

2019-11-08 01:49:52
字體:
來源:轉載
供稿:網友

實際上是通過編號對數組進行引用,第四章的字典則是通過名字引用

2.1序列概述

列表可以修改 元組不能修改

2.2通用序列操作

2.2.1索引

按編號獲取元素

test="hello world"PRint test[0] #獲取第1個元素print test[-1]#獲取倒數第一個元素

輸出結果

hdPress any key to continue . . .

2.2.2分片

test="hello world"print test[0:3] #獲取第1到第4個元素print test[1:-1]#獲取第二到倒數第一個元素print test[1:]#獲取第二到最后一個元素#更大的步長print test[1:-1:2]#獲取第二到倒數第一個元素,步長為2

輸出結果

helello worlello worldel olPress any key to continue . . .

2.2.3 序列相加

print [1,2,3]+[4,5,6]print "hello"+"world"#列表和字符串不能相加

輸出結果

[1, 2, 3, 4, 5, 6]helloworldPress any key to continue . . .

2.2.4乘法

print [1,2,3]*5print "hello"*5

輸出結果

[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]hellohellohellohellohelloPress any key to continue . . .

2.2.5成員資格

x="abcdefg"print "a" in xprint "x"in x

輸出結果

TrueFalsePress any key to continue . . .

2.2.6長度,最小值,最大值

x=[1,2,3,4]print len(x) #長度print max(x) #最大值print min(x) #最小值

輸出結果

441Press any key to continue . . .

2.3列表:Python的苦力

2.3.1list函數

print list("hello") #拆分字符串

輸出結果

['h', 'e', 'l', 'l', 'o']Press any key to continue . . .

2.3.2基本的列表操作

#1.改變列表:元素賦值x=[1,2,3]x[1]=4 #改第二元素為4print x#2.刪除元素x=["a","b","c"]del x[2] #刪除第三個元素print x#3.分片賦值x=["a","b","c"]x[1:]=list("asd") #修改第二道最后的元素為元組 asdprint xx[1:1]=list("asd") #相當于插入print xx[1:]=list("") #相當于刪除print x

輸出結果

[1, 4, 3]['a', 'b']['a', 'a', 's', 'd']['a', 'a', 's', 'd', 'a', 's', 'd']['a']Press any key to continue . . .

2.3.3列表方法

#1.append末尾追加x=[1,2,3]x.append(2)print x#2.count統計某個元素的詞數x=[1,2,3,4,2,12,3,1,1,1]print x.count(1)x=[1,[2,3],4,2,2,3,1,1,1]print x.count(2)print x.count([2,3])#3.extend擴展列表x=[1,2,3]y=[4,5]x.extend(y)print x#4.index找到某一項第一個匹配項的索引位置x=[1,2,3,4,2,12,3,1,1,1]print x.index(4)#5.insert插入x=[1,2,3,4,2,12,3,1,1,1]x.insert(3,"as")print x#6.pop移除列表中的一個元素x=[1,2,3,4,2,12,3,1,1,2]print x.pop()print x#7.remove移除某個值的第一個匹配項x=[1,2,3,4,2,12,3,1,1,2]x.remove(3)print x#8.reverse反向存放x=[1,2,3,4,2,12,3,1,1,2]x.reverse()print x#9.sort簡單排序x=[1,2,3,4,2,12,3,1,1,2]x.sort()print xy=sorted(x) #使y獲得x的排序print y#高級排序compareprint cmp(100,0)print cmp(1,2)

輸出結果

[1, 2, 3, 2]421[1, 2, 3, 4, 5]3[1, 2, 3, 'as', 4, 2, 12, 3, 1, 1, 1]2[1, 2, 3, 4, 2, 12, 3, 1, 1][1, 2, 4, 2, 12, 3, 1, 1, 2][2, 1, 1, 3, 12, 2, 4, 3, 2, 1][1, 1, 1, 2, 2, 2, 3, 3, 4, 12][1, 1, 1, 2, 2, 2, 3, 3, 4, 12]1-1Press any key to continue . . .

2.4元組:不可變序列

print 1,2,3print (1,2,3) #圓括號括起來print () #空元組print (2,) #生成只有一個元素的元組print 2*(2+3) #算式print 2*(2+3,)#元組#tuple序列轉化為元組print tuple([1,2,3])print tuple("as")

輸出結果

1 2 3(1, 2, 3)()(2,)10(5, 5)(1, 2, 3)('a', 's')Press any key to continue . . .
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 岳阳县| 诏安县| 南皮县| 文山县| 阿鲁科尔沁旗| 乌鲁木齐县| 蛟河市| 都匀市| 怀化市| 临夏县| 云林县| 鄂托克旗| 会同县| 淮南市| 武义县| 岳普湖县| 庄浪县| 竹溪县| 都安| 全州县| 土默特右旗| 南宫市| 锦屏县| 澳门| 诸城市| 安义县| 乌拉特后旗| 永兴县| 行唐县| 云霄县| 额济纳旗| 西城区| 凤庆县| 芜湖县| 太仆寺旗| 三江| 临颍县| 封丘县| 罗田县| 德格县| 彰化县|