Python -3-列表和元组
1.用list就可以像修改列表那样修改字符串了
>>> list('Hello')
['H', 'e', 'l', 'l', 'o']
可将任何序列作为list的参数
2.列表的基本操作
给元素赋值
>>> x = [1, 1, 1]
>>> x[1] = 2
>>> x
[1, 2, 1]
删除元素
>>> names = ['Alice', 'Beth', 'Cecil', 'Dee-Dee', 'Earl']
>>> del names[2]
>>> names
['Alice', 'Beth', 'Dee-Dee', 'Earl']
给切片赋值
>>> name = list('Perl')
>>> name
['P', 'e', 'r', 'l']
>>> name[2:] = list('ar')
>>> name
['P', 'e', 'a', 'r']
改变长度的赋值也可以
>>> name = list('Perl')
>>> name[1:] = list('ython')
>>> name
['P', 'y', 't', 'h', 'o', 'n']
插入新元素
>>> numbers = [1, 5]
>>> numbers[1:1] = [2, 3, 4]
>>> numbers
[1, 2, 3, 4, 5]
相反,也可以删除
>>> numbers
[1, 2, 3, 4, 5]
>>> numbers[1:4] = []
>>> numbers
[1, 5]
3.列表方法
append
>>> lst = [1, 2, 3]
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]
clear
>>> lst = [1, 2, 3]
>>> lst.clear()
>>> lst
【】
copy
常规复制只是将另一个名称关联到列表
>>> a = [1, 2, 3]
>>> b = a
>>> b[1] = 4
>>> a
[1, 4, 3]
copyj将b关联到a的副本
>>> a = [1, 2, 3]
>>> b = a.copy()
>>> b[1] = 4
>>> a
[1, 2, 3]
count
>>> ['to', 'be', 'or', 'not', 'to', 'be'].count('to')
2
>>> x = [[1, 2], 1, 1, [2, 1, [1, 2]]]
>>> x.count(1)
2
>>> x.count([1, 2])
1
extend
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a.extend(b)
>>> a
[1, 2, 3, 4, 5, 6]
与加法的区别:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a + b
[1, 2, 3, 4, 5, 6]
>>> a
[1, 2, 3]
如果要实现这个>>> a = a + b,加法的效率将比extend低
index
查找指定值第一次出现的索引
>>> knights = ['We', 'are', 'the', 'knights', 'who', 'say', 'ni']
>>> knights.index('who')
4
>>> knights.index('herring')
Traceback (innermost last):
File "<pyshell>", line 1, in ?
knights.index('herring')
ValueError: list.index(x): x not in list
找不到就报错
insert
>>> numbers = [1, 2, 3, 5, 6, 7]
>>> numbers.insert(3, 'four')
>>> numbers
[1, 2, 3, 'four', 5, 6, 7]
pop
>>> x = [1, 2, 3]
>>> x.pop()
3
>>> x
[1, 2]
>>> x.pop(0)
1
>>> x
[2]
返回弹出的值
与append相对
remove
删除第一个为指定值得元素
>>> x = ['to', 'be', 'or', 'not', 'to', 'be']
>>> x.remove('be')
>>> x
['to', 'or', 'not', 'to', 'be']
reverse
>>> x = [1, 2, 3]
>>> x.reverse()
>>> x
[3, 2, 1]
sort
就地排序
>>> x = [4, 6, 2, 1, 7, 9]
>>> x.sort()
>>> x
[1, 2, 4, 6, 7, 9]
>>> y = x.sort() # Don't do this!
>>> print(y)
None
另一个sorted不在原变量排序有返回值
>>> x = [4, 6, 2, 1, 7, 9]
>>> y = sorted(x)
>>> x
[4, 6, 2, 1, 7, 9]
>>> y
[1, 2, 4, 6, 7, 9]
>>> sorted('Python')
['P', 'h', 'n', 'o', 't', 'y']
sorted可用于任何序列(可迭代对象),但总返回一个列表
高级排序
这里有两个可选参数:key和reverse
>>> x = ['aardvark', 'abalone', 'acme', 'add', 'aerate']
>>> x.sort(key=len)
>>> x
['add', 'acme', 'aerate', 'abalone', 'aardvark']
>>> x = [4, 6, 2, 1, 7, 9]
>>> x.sort(reverse=True)
>>> x
[9, 7, 6, 4, 2, 1]
元组
与列表唯一差别在于元组不能修改
创建元组
>>> 1, 2, 3
(1, 2, 3)
>>> (1, 2, 3)
(1, 2, 3)
空元组(列表也是这样)
>>> ()
()
加上逗号就是元组
>>> 42
42
>>> 42,
(42,)
>>> (42,)
(42,)
>>> 3 * (40 + 2)
126
>>> 3 * (40 + 2,)
(42, 42, 42)
tuple与list类似,将一个序列作为参数,转换为元组
>>> tuple([1, 2, 3])
(1, 2, 3)
>>> tuple('abc')
('a', 'b', 'c')
>>> tuple((1, 2, 3))
(1, 2, 3)
其它操作和列表差不多
>>> x = 1, 2, 3
>>> x[1]
2
>>> x[0:2]
(1, 2)