首页 > 编程 > 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 . . .
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表