第三课:序列(sequence)
1、序列是一种有顺序的元素的集合
序列可以包含1个或多个元素,也可以不包括任何元素;
序列中的元素可以是【基础数据类型】中任一种,也可以是【别的序列】。
s1 = (2, 1.3, 'love', 5.6, 9, 12, False) # s1是一个tuple s2 = [True, 5, 'smile'] # s2是一个list print s1,type(s1) print s2,type(s2) 输出:
(2, 1.3, 'love', 5.6, 9, 12, False) <type 'tuple'> [True, 5, 'smile'] <type 'list'> s3 = [a,[1,2,'123']] #一个序列可以作为别的序列的元素 s4 = [] #空序列
2、序列有两种:tuple(元组)、list(表)
tuple和list的区别:一旦建立,tuple的元素不能变更,list的元素可以变更。
3、序列元素的引用
序列的下标从0开始
print s2[0] print s1[2] print s3[1][2]
list的元素可以变更,直接赋值即可,如下
其中给元素赋值,可以赋给它基础类型和tuple和list。
s2[1] = 3.0
print s2[1]
s2 = [True, 5, 'smile'] # s2是一个list
s3 = [1,[1,2,3]]
print s2,type(s2)
print s3,type(s3)
s2[0] = 1
s3[1] = 1s3[1] = (1,2,3)
print s2,type(s2)
print s3,type(s3)
输出:
[True, 5, 'smile'] <type 'list'>
[1, [1, 2, 3]] <type 'list'>
[1, 5, 'smile'] <type 'list'>
[1, 1] <type 'list'>
s3[1] = (1,2,3)
输出:[1, (1, 2, 3)] <type 'list'>s3 = [1,(1,2,3)]
s3[1] = [1,2,3]
print s3,type(s3)
输出:[1, [1, 2, 3]] <type 'list'>
其它引用方式
样式:[下限,上限,步长]
print s1[:5] # 从开始到下标4 (下标5的元素 不包括在内) print s1[2:] # 从下标2到最后 print s1[0:5:2] # 从下标0到下标4 (下标5不包括在内),每隔2取一个元素 (下标为0,2,4的元素) print s1[2:0:-1] # 从下标2到下标1 从上面可以看到,在范围引用的时候,如果写明上限,那么这个上限本身不包括在内。 尾部元素引用 print s1[-1] # 序列最后一个元素 print s1[-3] # 序列倒数第三个元素 同样,如果s1[0:-1], 那么最后一个元素不会被引用 (再一次,不包括上限元素本身)
字符串是一种特殊的元素,因此可以执行元组相应的操作
str='123456' print str[2:4]
第四课:运算
算术:+、-、*、/、%、**(乘方)
运算:>、>=、<、<=、==、!=、in
逻辑:and、or、not
>>> 0 == True False >>> 0 == False True >>> not 0 True >>> 1 == True True >>> 1 == False False >>> not 1 False >>> -1 == True False >>> -1 == False False >>> not -1 False
在Python中,以下数值会被认为是false,其它的都是True;
1)数字0,包括0.0
2)空字符串,''和""
3)空集合,[]、{}、()