资源简介
(共103张PPT)
第3章 序列
Chap3 Sequence
There is a road in the mountains of books, and diligence is the path
序列
3.1
2
序列
aStr = 'Hello, World!'
aList = [2, 3, 5, 7, 11]
aTuple = ('Sunday', 'happy' )
x = range(10)
pList = [('AXP', 'American Express Company', '78.51'),
('BA', 'The Boeing Company', '184.76'),
('CAT', 'Caterpillar Inc.', '96.39'),
('CSCO', 'Cisco Systems, Inc.', '33.71'),
('CVX', 'Chevron Corporation', '106.09')]
3
序列是一种最基本最重要的数据结构
4
A
Strings
字符串
B
Lists
列表
C
Tuples
元组
D
range objects
range对象
3.1.1 索引
5
序列的索引
序列类型对象一般有多个成员组成,每个成员通常称为元素,每个元素都可以通过索引(index)进行访问,索引用方括号“[]”表示。如:
6
sequence[index]
序列的索引
7
week 0 1 2 3 4 5 6
'Monday' 'Tuesday' 'Wednesday' 'Thursday' 'Friday' 'Saturday' 'Sunday'
-7 -6 -5 -4 -3 -2 -1
序列
0
-N
1
-(N-1)
2
-(N-2)
…
N-2
-2
N-1
-1
访问模式
元素从0开始通过下标偏移量访问
一次可访问一个或多个元素
索引的使用
8
>>> aList = ['Mon.', 'Tues.', 'Wed.', 'Thur.', 'Fri.', 'Sat.', 'Sun.']
>>> aList[1]
'Tues.'
>>> aList[-1]
'Sun.'
>>> aStr = 'apple'
>>> aStr[1]
'p'
Source
序列相关操作
9
值比较
对象身份比较
布尔运算
获取
重复
连接
成员判断
序列类型转换内建函数
序列类型可用内建函数
标准
类型
运算符
序列
类型
运算符
内建
函数
3.1.2 标准类型运算
10
标准类型运算符
< >
<= >=
== !=
值比较
is
is not
对象身份比较
not
and
or
布尔运算
11
值比较
12
>>> 'apple' < 'banana'
True
>>> [1,3,5] != [2,4,6]
True
>>> aList[1] == 'Tues.'
True
>>> [1, 'Monday'] < [1, 'Tuesday']
True
Source
>>> ['o', 'k'] < ('o', 'k')
Traceback (most recent call last):
File "", line 1, in
['o', 'k'] < ('o', 'k')
TypeError: unorderable types: list() < tuple()
>>> [1 , [2 , 3]] < [1 , ['a' , 3]]
Traceback (most recent call last):
File "", line 1, in
[1 , [2 , 3]] < [1 , ['a' , 3]]
TypeError: unorderable types: int() < str()
Source
对象身份比较
13
>>> aTuple = ('BA', 'The Boeing Company', '184.76')
>>> bTuple = aTuple
>>> bTuple is aTuple
True
>>> cTuple = ('BA', 'The Boeing Company', '184.76')
>>> aTuple is cTuple
False
>>> aTuple == cTuple
True
Source
布尔(逻辑)运算
14
>>> ch = 'k'
>>> 'a' <= ch <= 'z' or 'A' <= ch <= 'Z‘
True
Source
3.1.3 通用序列类型操作
15
序列类型运算符
16
x in s
x not in s
s + t
s * n, n * s
s[i]
s[i:j]
s[i:j:k]
切片
17
0 1 2 3 4 5 6
切片操作的形式为:
sequence[startindex : endindex]
索引值
>>> aStr = 'American Express Company'
>>> aStr[9: 16]
'Express'
Source
切片
18
>>> aList = ['Mon.', 'Tues.', 'Wed.', 'Thur.', 'Fri.', 'Sat.', 'Sun.']
>>> aList [0: 5]
['Mon.', 'Tues.', 'Wed.', 'Thur.', 'Fri.']
>>> aList[: 5]
['Mon.', 'Tues.', 'Wed.', 'Thur.', 'Fri.']
>>> aList[5: 7]
['Sat.', 'Sun.']
Source
切片
19
>>> aList[-2: -1]
['Sat.']
>>> aList[-2: -3]
[]
>>> aList[-2:]
['Sat.', 'Sun.']
>>> aList[:]
['Mon.', 'Tues.', 'Wed.', 'Thur.', 'Fri.', 'Sat.', 'Sun.']
Source
切片
20
切片操作的另一种格式,可以选择切片操作时的步长:
sequence[startindex : endindex : steps]
aList[0: 5] aList[0: 5: 1]
0 1 2 3 4 5 6
切片
21
>>> aList = ['Mon.', 'Tues.', 'Wed.', 'Thur.', 'Fri.', 'Sat.', 'Sun.']
>>> aList[1: 6: 3]
['Tues.', 'Fri.']
>>> aList[::3]
['Mon.', 'Thur.', 'Sun.']
>>> aList[::-3]
['Sun.', 'Thur.', 'Mon.']
>>> aList[5: 1: -2]
['Sat.', 'Thur.']
Source
切片
22
>>> aStr = 'apple'
>>> aStr[0: 3]
'app'
>>> aTuple = (3, 2, 5, 1, 4, 6)
>>> aTuple[1: : 2]
(2, 1, 6)
Source
切片
23
>>> aList = ['Mon.', 'Tues.', 'Wed.', 'Thur.', 'Fri.', 'Sat.', 'Sun.']
>>> day = aList[int(input('The day of the week(1-7): ')) - 1]
The day of the week(1-7): 5
>>> print( 'Today is ' + day + '.')
Today is Fri..
Source
切片
24
>>> week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
>>> print(week[1], week[-2], '\n', week[1:4], '\n', week[:6], '\n', week[::-1])
Tuesday Saturday
['Tuesday', 'Wednesday', 'Thursday']
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
['Sunday', 'Saturday', 'Friday', 'Thursday', 'Wednesday', 'Tuesday', 'Monday']
Source
重复
25
重复操作的形式为:
sequence * copies
>>> 'apple' * 3
'appleappleapple'
>>> (1, 2, 3) * 2
(1, 2, 3, 1, 2, 3)
>>> aTuple = (3, 2, 5, 1)
>>> aTuple * 3
(3, 2, 5, 1, 3, 2, 5, 1, 3, 2, 5, 1)
>>> ['P' , 'y', 't', 'h', 'o', 'n'] * 2
['P', 'y', 't', 'h', 'o', 'n', 'P', 'y', 't', 'h', 'o', 'n']
Source
连接
26
连接操作的形式为:
sequence1 + sequence2
>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> (1, 2, 3) + (4, 5, 6)
(1, 2, 3, 4, 5, 6)
>>> 'pine' + 'apple'
'pineapple'
>>> ['t', 'h', 'e'] + 'apple'
Traceback (most recent call last):
File "", line 1, in
['t', 'h', 'e'] + 'apple'
TypeError: can only concatenate list (not "str") to list
Source
判断成员
27
>>> aList = ['Mon.', 'Tues.', 'Wed.', 'Thur.', 'Fri.', 'Sat.', 'Sun.']
>>> 'Mon.' in aList
True
>>> 'week' in aList
False
>>> 'week' not in aList
True
Source
判断一个元素是否属于一个序列操作的形式为:
obj in sequence
obj not in sequence
判断成员
28
>>> username = ['Jack', 'Tom', 'Halen', 'Rain']
>>> input("please input your name: ") in username
please input your name: Halen
True
Source
3.1.4 序列类型函数
29
序列类型转换内建函数
30
list()
str()
tuple()
>>> list('Hello, World!')
['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']
>>> tuple("Hello, World!")
('H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!')
>>> list((1, 2, 3))
[1, 2, 3]
>>> tuple([1, 2, 3])
(1, 2, 3)
Source
31
序列类型其他常用内建函数
32
enumerate() len()
reversed() sorted()
max() sum()
min() zip()
>>> aStr = 'Hello, World!'
>>> len(aStr)
13
>>> sorted(aStr)
[' ', '!', ',', 'H', 'W', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r']
Source
序列类型其他常用内建函数
33
>>> aStr = 'Hello, World!'
>>> len(aStr)
13
Source
>>> nList = [3, 2, 5, 1]
>>> sorted(nList)
[1, 2, 3, 5]
>>> nList
[3, 2, 5, 1]
Source
len()
sorted()
序列类型其他常用内建函数
34
>>> nList = [3, 2, 5, 1]
>>> reversed(nList)
>>> list(reversed(nList))
[1, 5, 2, 3]
Source
reversed()
逆序排列
序列类型其他常用内建函数
35
元素必须是数值型
>>> sum(['a', 'b', 'c'])
Traceback (most recent call last):
File "", line 1, in
sum(['a', 'b', 'c'])
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> sum([1, 2, 3.5])
6.5
Source
sum()
序列类型其他常用内建函数
36
>>> aList = ['Mon.', 'Tues.', 'Wed.', 'Thur.', 'Fri.', 'Sat.', 'Sun.']
>>> max(aList)
'Wed.'
>>> max([1, 2.5, 3])
3
>>> max([1, 5, 3],[1, 2.5, 3])
[1, 5, 3]
>>> max([1, 5, 3, 1],[1, 9, 3])
[1, 9, 3]
Source
max()和min()
序列类型其他常用内建函数
37
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start = 1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
Source
enumerate()
返回元素的索引和值组成的元组
序列类型其他常用内建函数
38
>>> list(zip('hello', 'world'))
[('h', 'w'), ('e', 'o'), ('l', 'r'), ('l', 'l'), ('o', 'd')]
Source
zip()
第N个元素是由每个可迭代对象的第N个元素组成的元组
字符串
3.2
39
3.2.1 字符串的表示
40
字符串的表示形式
41
>>> aStr = 'The Boeing Company'
>>> bStr = "The Boeing Company "
>>> cStr = '''The Boeing
company'''
>>> aStr
'The Boeing Company'
>>> bStr
'The Boeing Company'
>>> cStr
'The Boeing\nCompany'
Source
单引号
三引号
双引号
字符串的表示形式
42
>>> dStr = "I'm a student."
>>> dStr
"I'm a student."
>>> eStr = '"No pain, No gain." is a good saying.'
>>> eStr
'"No pain, No gains." is a good saying.'
>>> "break" 'fast' # "break""fast"或'break''fast'等形式亦可
'breakfast'
Source
字符串的表示形式
43
>>> cStr = '''The Boeing
company'''
>>> cStr
'The Boeing\nCompany'
>>> fStr = '''It's said that
... where there is a will, there is a way.'''
>>> fStr
"It's said that\nwhere there is a will, there is a way."
Source
三引号
分行输入
字符串的创建和访问
44
>>> aStr = 'The Boeing Company'
>>> print("football")
football
Source
>>> aStr = 'The Boeing Company'
>>> hStr = aStr[:4] + 'IBM' + aStr[-8:]
>>> hStr
'The IBM Company'
Source
创建方式:
访问方式:
直接
输出
赋值
切片
字符串的创建和访问——不可变
45
>>> hStr
'The IBM Company'
>>> hStr = ''
>>> hStr
''
>>> testStr = 'hello'
>>> testStr[0] = 'H'
Traceback (most recent call last):
File "", line 1, in
testStr[0] = 'H'
TypeError: 'str' object does not support item assignment
Source
字符串的表示形式
46
>>> gStr = r'd:\python\n.py'
>>> gStr
'd:\\python\\n.py'
Source
转义
字符
常用转义字符
47
字符 说明
\t 横向制表符
\n 换行
\r 回车
\" 双引号
\' 单引号
\\ 反斜杠
\(在行尾时) 续行符
\OOO 八进制数OOO代表的字符
\xXX 十六进制数XX代表的字符
>>> aStr = '\101\t\x41\n'
>>> bStr = '\141\t\x61\n'
>>> print(aStr, bStr)
A A
a a
Source
字符串常用方法
48
capitalize() center() count() encode() endswith() find()
format() index() isalnum() isalpha() isdigit() islower()
isspace() istitle() isupper() join() ljust() lower()
lstrip() maketrans() partition() replace() rfind() rindex()
rjust() rpartition() rstrip() split() splitlines() startswith()
strip() swapcase() title() translate() upper() zfill()
49
50
51
52
字符串常用方法
53
>>> aStr = 'Python!'
>>> aStr.center(11)
' Python! '
Source
center()
>>> bStr = 'No pain, No gain.'
>>> bStr.count('no')
0
>>> bStr.count('No')
2
Source
count()
11宽度居中显示
字符串小例子
54
给出一个字符串,不区分大小写,字符串中可能包含‘A’-‘Z’,‘a’-‘z’,‘ ’(空格)等字符。输出字母a(包括大小写)出现的次数。测试数据:abc&ABC。
?
# Filename: char_count.py
s1 = "abc&ABC"
s = s1.lower()
n = s.count("a")
print(n)
File
字符串常用方法
55
>>> bStr = 'No pain, No gain. ' # 逗号后面有一个空格!
>>> bStr.find('No')
0
>>> bStr.find('no')
-1
>>> bStr.find('No', 3)
9
>>> bStr.find('No', 3, 10)
-1
>>> bStr.find('No', 3, 11)
9
Source
find()
返回出现的第一个位置(索引号)
字符串常用方法
56
>>> bStr = 'No pain, No gain. ' # 逗号后面有一个空格!
>>> bStr.index('no')
Traceback (most recent call last):
File "", line 1, in
bStr.index('no')
ValueError: substring not found
>>> bStr.index('No', 3, 10)
Traceback (most recent call last):
File "", line 1, in
bStr.index('No', 3, 10)
ValueError: substring not found
Source
index()
字符串常用方法
57
>>> ' love '.join(['I', 'Python!'])
'I love Python!'
>>> ' '.join(['Hello,', 'World'])
'Hello, World'
>>> '->'.join(('BA', 'The Boeing Company', '184.76'))
'BA->The Boeing Company->184.76'
Source
join()
字符串常用方法
58
>>> cStr = 'Hope is a good thing.'
>>> cStr.replace("Hope", 'Love')
'Love is a good thing.'
Source
replace()
字符串常用方法
59
split()
>>> '2020 1 1'.split()
['2020', '1', '1']
>>> dStr = 'I am a student.'
>>> dStr[:-1].split()
['I', 'am', 'a', 'student']
>>> '2020.1.1'.split('.')
['2020', '1', '1']
Source
返回元素组成的列表
字符串的应用
60
有一些从网络上下载的类似如下形式的一些句子:
What do you think of this saying "No pain, No gain"
对于句子中双引号中的内容,首先判断其是否满足标题格式,不管满足与否最终都将其转换为标题格式输出。
?
# Filename: totitle.py
aStr = 'What do you think of this saying "No pain, No gain" '
lindex = aStr.index('\"',0,len(aStr))
rindex = aStr.rindex('\"',0,len(aStr))
tempStr = aStr[lindex+1:rindex]
if tempStr.istitle():
print('It is title format.')
else:
print('It is not title format.')
print(tempStr.title())
File
字符串的应用
61
tempstr= aStr.split("\"")[1]
列表
3.3
62
列表
63
B
A
C
经典的
序列类型
可变的容器
包含
不同类型元素
3.3.1 列表的表示
64
列表的表示
65
>>> aList = ['P' , 'y', 't', 'h', 'o', 'n']
>>> pList = [1, 'BA', 'The Boeing Company', 184.76]
Source
中括号
列表的创建
66
>>> aList = []
>>> bList = [1, 'BA', 'The Boeing Company', 184.76]
>>> cList = [x for x in range(1, 10, 2)]
>>> dList = list('Python')
Source
空括号
赋值
List
内建函数
列表
解析
列表的创建
67
可扩展的容器对象
包含不同类型对象
>>> aList = list('Hello.')
>>> aList
['H', 'e', 'l', 'l', 'o', '.']
>>> aList = list('hello.')
>>> aList
['h', 'e', 'l', 'l', 'o', '.']
>>> aList[0] = 'H'
>>> aList
['H', 'e', 'l', 'l', 'o', '.']
Source
>>> bList = [1, 2, 'a', 3.5]
Source
小写h改成大写H
列表的创建
aList = [1, 2, 3, 4, 5]
names = ['Zhao', 'Qian', 'Sun', 'Li']
bList = [3, 2, 1, 'Action']
pList = [('AXP', 'American Express Company', '78.51'),
('BA', 'The Boeing Company', '184.76'),
('CAT', 'Caterpillar Inc.', '96.39'),
('CSCO', 'Cisco Systems, Inc.', '33.71'),
('CVX', 'Chevron Corporation', '106.09')]
68
列表的操作
69
>>> pList = [('AXP', 'American Express Company', '78.51'),
('BA', 'The Boeing Company', '184.76'),
('CAT', 'Caterpillar Inc.', '96.39'),
('CSCO', 'Cisco Systems, Inc.', '33.71'),
('CVX', 'Chevron Corporation', '106.09')]
>>> pList[1]
('BA', 'The Boeing Company', '184.76')
>>> pList[1][1]
'The Boeing Company'
Source
列表的操作
70
>>> eList = list('hello')
['h', 'e', 'l', 'l', 'o']
>>> eList[0] = 'H'
>>> eList
['H', 'e', 'l', 'l', 'o']
Source
可变的列表可以修改元素值
71
列表的方法
72
append()
copy()
count()
extend()
index()
insert()
pop()
remove()
reverse()
sort()
参数的作用:list.sort(key=None, reverse=False)
>>> numList = [3, 11, 5, 8, 16, 1]
>>> fruitList = ['apple', 'banana', 'pear', 'lemon', 'avocado']
>>> numList.sort(reverse = True)
>>> numList
[16, 11, 8, 5, 3, 1]
>>> fruitList.sort(key = len)
>>> fruitList
[‘pear’, ‘apple’, ‘lemon’, ‘banana’, ‘avocado’]#按长度进行排序
Source
列表的方法
73
>>> aList = [1, 2, 3]
>>> aList.append(4)
>>> aList
[1, 2, 3, 4]
>>> aList.append([5, 6])
>>> aList
[1, 2, 3, 4, [5, 6]]
>>> aList.append('Python!')
>>> aList
[1, 2, 3, 4, [5, 6], 'Python!']
Source
append()
将参数“整个”添加到列表尾部
>>> bList = [1, 2, 3]
>>> bList.extend([4])
>>> bList
[1, 2, 3, 4]
>>> bList.extend([5, 6])
>>> bList
[1, 2, 3, 4, 5, 6]
>>> bList.extend('Python!')
>>> bList
[1, 2, 3, 4, 5, 6, 'P', 'y', 't', 'h', 'o', 'n', '!']
Source
列表的方法
74
extend()
每个元素单个添加到列表尾部
列表的方法
75
>>> bList = [1, 2, 3]
>>> bList.extend(4)
Traceback (most recent call last):
File "", line 1, in
bList.extend(4)
TypeError: 'int' object is not iterable
Source
extend()
>>> a = [1, 2, [3, 4]]
>>> b = a.copy() # b = a[:]也是浅拷贝
>>> b
[1, 2, [3, 4]]
>>> b[0], b[2][0] = 5, 5
>>> b
[5, 2, [5, 4]]
>>> a
[1, 2, [5, 4]]
Source
列表的方法
76
>>> b[2][0] is a[2][0]
True
>>> b[0] is a[0]
False
Source
copy()
浅拷贝
只复制父对象不复制内部子对象
>>> import copy
>>> a = [1, 2, [5, 4]]
>>> c = copy.deepcopy(a)
>>> c
[1, 2, [5, 4]]
>>> c[0], c[2][0] = 8, 8
>>> c
[8, 2, [8, 4]]
>>> a
[1, 2, [5, 4]]
Source
列表的方法
77
deepcopy()
深拷贝
既复制父对象也复制内部子对象
>>> scores = [7, 8, 8, 8, 8.5, 9, 9, 9, 10, 10]
>>> scores.pop()
10
>>> scores
[7, 8, 8, 8, 8.5, 9, 9, 9, 10]
>>> scores.pop(4)
8.5
>>> scores
[7, 8, 8, 8, 9, 9, 9, 10]
Source
列表的方法
78
pop()
不带参数的是删除列表最后一个元素
>>> jScores = [7, 8, 8, 8, 9, 9, 9, 10]
>>> jScores.remove(9)
>>> jScores
[7, 8, 8, 8, 9, 9, 10]
Source
列表的方法
79
remove()
删除列表中第一个值为“9”的元素
删除第一个找到的对象
>>> week = ['Mon.', 'Tues.', 'Wed.', 'Thur.', 'Fri.', 'Sat.', 'Sun.']
>>> week.reverse()
>>> week
['Sun.', 'Sat.', 'Fri.', 'Thur.', 'Wed.', 'Tues.', 'Mon.']
Source
列表的方法
80
reverse()
列表的方法
81
序列类型的内建函数
返回的是序列逆序排序后的迭代器,原列表内容不变。
reversed()
列表的方法
在原列表上直接翻转,并得到逆序列表,改变原列表内容。
列表.reverse()
字符串和元组(字符串和元组都是不可变的)没有reverse()方法
Source
>>> jScores = [9, 9, 8.5, 10, 7, 8, 8, 9, 8, 10]
>>> jScores.sort()
>>> jScores
[7, 8, 8, 8, 8.5, 9, 9, 9, 10, 10]
>>> numList = [3, 11, 5, 8, 16, 1]
>>> fruitList = ['apple', 'banana', 'pear', 'lemon', 'avocado']
>>> numList.sort(reverse = True)
>>> numList
[16, 11, 8, 5, 3, 1]
>>> fruitList.sort(key = len)
>>> fruitList
['pear', 'apple', 'lemon', 'banana', 'avocado']
列表的方法
82
sort()
根据值进行排序
列表的方法
83
序列类型的内建函数
返回的是排序后的新列表,原列表内容不变。
sorted()
列表的方法
对原列表排序,改变原列表内容。
列表.sort()
字符串和元组(字符串和元组都是不可变的)没有sort()方法
列表的应用
84
某学校组织了一场校园歌手比赛,每个歌手的得分由10名评委和观众决定,最终得分的规则是去掉10名评委所打分数的一个最高分和一个最低分,再加上所有观众评委分数后的平均值。评委打出的10个分数为:9、9、8.5、10、7、8、8、9、8和10,观众评委打出的综合评分为9,请计算该歌手的最终得分。
?
列表的应用
85
[7, 8, 8, 8, 8.5, 9, 9, 9, 10, 10]
[8, 8, 8, 8.5, 9, 9, 9, 10]
[8, 8, 8, 8.5, 9, 9, 9, 10, 9]
8.72222222222
# Filename: scoring.py
jScores = [9, 9, 8.5, 10, 7, 8, 8, 9, 8, 10]
aScore = 9
jScores.sort()
jScores.pop()
jScores.pop(0)
jScores.append(aScore)
aveScore = sum(jScores)/len(jScores)
print(aveScore)
File
列表的应用
86
有一份参加Python课程的学号名单B01,B02,B03,B05,B08,B10,请计算共有多少同学参与了本课程。请分别用列表和字符串的方法来解决这个问题。
?
列表的应用
87
# Filename: count.py
lst = ['B01','B02','B03','B05','B08','B10']
s = "B01,B02,B03,B05,B08,B10"
num1 = len(lst)
print(num1)
num2 = s.count(',') + 1
num3 = len(s.split(','))
print(num2, num3)
File
元组
3.4
88
元组的创建
89
>>> aTuple = (1, 2, 3)
>>> aTuple
(1, 2, 3)
>>> 2020,
(2020,)
>>> k = 1, 2, 3
>>> k
(1, 2, 3)
Source
圆括号
元组的操作
90
>>> bTuple = (['Monday', 1], 2,3)
>>> bTuple
(['Monday', 1], 2, 3)
>>> bTuple[0][1]
1
>>> len(bTuple)
3
>>> bTuple[1:]
(2, 3)
Source
序列通用:
切片、求长度
元组的操作
91
Source
>>> aList = ['AXP', 'BA', 'CAT']
>>> aTuple = ('AXP', 'BA', 'CAT')
>>> aList[1] = 'Alibiabia'
>>> print(aList)
['AXP', 'Alibiabia', 'CAT']
>>> aTuple1[1]= 'Alibiabia'
Traceback (most recent call last):
File "", line 1, in
aTuple1[1]= 'Alibiabia'
NameError: name 'aTuple1' is not defined
>>> aTuple.sort()
Traceback (most recent call last):
File "", line 1, in
aTuple.sort()
AttributeError: 'tuple' object has no attribute 'sort'
元组不可变
元组
92
>>> aTuple = (3, 5, 2, 4)
>>> sorted(aTuple)
[2, 3, 4, 5]
>>> aTuple
(3, 5, 2, 4)
>>> aTuple.sort()
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'tuple' object has no attribute 'sort'
Source
>>> aList = [3, 5, 2, 4]
>>> aList
[3, 5, 2, 4]
>>> sorted(aList)
[2, 3, 4, 5]
>>> aList
[3, 5, 2, 4]
>>> aList.sort()
>>> aList
[2, 3, 4, 5]
Source
元组
93
序列的内建函数
返回排序新列表,原列表内容不变
sorted()
元组没有sort方法。
sort()
3.4.2 元组的其他特性和作用
94
元组特性
95
>>> bTuple = (1, 2, [3, 4])
>>> bTuple[2] = [5, 6]
Traceback (most recent call last):
File "", line 1, in
bTuple[2] = [5, 6]
TypeError: 'tuple' object does not support item assignment
>>> bTuple[2][0] = 5
>>> bTuple
(1, 2, [5, 4])
Source
元组的
可变元素可变
元组的作用
元组用在什么地方?
在映射类型中当作键使用
函数的特殊类型参数
未明确定义的一组对象
96
1,2,3
元组作为函数特殊返回类型
>>> def foo():
return 1, 2, 3
>>> foo()
(1, 2, 3)
Source
返回对象的个数 返回类型
0 None
1 object
>1 tuple
97
range对象
3.5
98
range对象
用range()函数生成range对象,执行时一边计算一边产生值(类似一个生成器),生成一个不可变的整数序列
99
range(start, end, step=1)
range(start, end)
range(end)
range对象
100
>>> list(range(3, 11))
[3, 4, 5, 6, 7, 8, 9, 10]
>>> list(range(11))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(range(3, 11, 2))
[3, 5, 7, 9]
Source
>>> list(range(0, -10, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> list(range(0))
[]
>>> list(range(1, 0))
[]
Source
小结
序列
字符串
列表
元组
range对象
101
102
103
展开更多......
收起↑