列表是内容可变的序列
1、list函数:可根据字符串创建列表
>>> stringlist = list('hello')
>>> stringlist
['h', 'e', 'l', 'l', 'o']
2、列表的基本操作:适用于序列的所有标准操作
改变列表的方法:元素赋值、删除元素、分片赋值
1)元素赋值(注:不能给一个位置不存在的元素赋值)
>>> x = [1, 1, 1]
>>> x[1] = 2
>>> x
[1, 2, 1]
2)删除元素,使用del语句
>>> x = [1, 2, 1]
>>> del x[1]
>>> x
[1, 1]
3)分片赋值
一次为多个元素赋值 | 不定长替换 | 插入新元素 | 删除元素 |
>>> name = list('Perl') >>> name ['P', 'e', 'r', 'l'] >>> name[1:] = list('ar') >>> name ['P', 'a', 'r'] | >>> name = list('Pear') >>> 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、列表的方法
1)append方法:列表末尾追加新对象
>>> lst = [1, 2, 3]
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]
2)count方法:统计某个元素在列表中出现的次数
>>> lst = ['to', 'be', 'or', 'not', 'to', 'be']
>>> lst.count('to')
2
3)extend方法:在列表的末尾一次性追加另一个序列的多个值
>>> a=[1, 2, 3]
>>> b=[4, 5, 6]
>>> a.extend(b)
注意:与连接的区别,extend方法直接修改原列表
4)index方法:返回第一个匹配元素的索引位置
>>> knights = ['we', 'are', 'the', 'knight', 'who', 'say', 'ni']
>>> knights.index('who')
4
5)insert方法:将对象插入到列表中
说明:insert(index,'string'),在索引index处插入'string'
>>> numbers = [1, 2, 3, 4, 5, 6, 7]
>>> numbers.insert(3,'four')
>>> numbers
[1, 2, 3, 'four', 4, 5, 6, 7]
6)pop方法:移除列表中一个元素(默认最后一个),并返回该元素
>>> knights = ['we', 'are', 'the', 'knight', 'who', 'say', 'ni']
>>> knights
['we', 'are', 'the', 'knight', 'who', 'say', 'ni']
>>> knights.pop(3)
'knight'
>>> knights
['we', 'are', 'the', 'who', 'say', 'ni']
注:唯一一个既能修改列表又能返回元素值的列表方法
7)remove方法:移除列表中某一个值的第一个匹配项,但无返回值,与pop相反
>>> x = ['to', 'be', 'or', 'not', 'to', 'be']
>>> x.remove('be')
>>> x
['to', 'or', 'not', 'to', 'be']
8)reverse方法:将列表中的元素反向存放
>>> x = [1, 2, 3]
>>> x.reverse()
>>> x
[3, 2, 1]
9)sort方法:在原位置进行排序,即对原列表进行排序
>>> x = [4, 6, 2, 1, 7, 9]
>>> x.sort()
>>> x
[1, 2, 4, 6, 7, 9]
获取已排列的列表副本方法: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]
10)高级排序:sort的两个可选参数:key和reverse
说明:key定义按照什么排序
>>> x = ['arrdvark', 'abalone', 'acme', 'add', 'aerate']
>>> x.sort(key=len)
>>> x
['add', 'acme', 'aerate', 'abalone', 'arrdvark']
>>> x = [4, 6, 2, 1, 7, 9]
>>> x.sort(reverse=True)
>>> x
[9, 7, 6, 4, 2, 1]
元组:不可变序列,圆括号括起来,内部使用逗号分隔
空元组:()
一个值的元组:(42,) ,即使只有一个值,必须加上逗号
tuple函数:以一个序列作为参数并把它转换为元组
>>> tuple([1, 2, 3])
(1, 2, 3)