python学习笔记三:列表
列表是内容可变的序列1、list函数:可根据字符串创建列表
>>>stringlist = list('hello')
>>>stringlist
['h','e', 'l', 'l', 'o']
2、列表的基本操作:适用于序列的所有标准操作
改变列表的方法:元素赋值、删除元素、分片赋值
1)元素赋值(注:不能给一个位置不存在的元素赋值)
>>>x =
>>>x = 2
>>>x
2)删除元素,使用del语句
>>> x =
>>>del x
>>>x
3)分片赋值
一次为多个元素赋值
不定长替换
插入新元素
删除元素
>>> name = list('Perl')
>>> name
['P', 'e', 'r', 'l']
>>> name = list('ar')
>>> name
['P', 'a', 'r']
>>> name = list('Pear')
>>> name = list('ython')
>>> name
['P', 'y', 't', 'h', 'o', 'n']
>>> numbers=
>>> numbers =
>>> numbers
>>> numbers
>>> numbers = []
>>> numbers
3、列表的方法
1)append方法:列表末尾追加新对象
>>>lst =
>>>lst.append(4)
>>> lst
2)count方法:统计某个元素在列表中出现的次数
>>> lst =['to', 'be', 'or', 'not', 'to', 'be']
>>>lst.count('to')
2
3)extend方法:在列表的末尾一次性追加另一个序列的多个值
>>> a=
>>> b=
>>>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 =
>>>numbers.insert(3,'four')
>>>numbers
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 =
>>>x.reverse()
>>> x
9)sort方法:在原位置进行排序,即对原列表进行排序
>>> x =
>>>x.sort()
>>> x
获取已排列的列表副本方法:sorted函数,原列表保持不变
>>> x =
>>> y =sorted(x)
>>> x
>>> y
10)高级排序:sort的两个可选参数:key和reverse
说明:key定义按照什么排序
>>> x =['arrdvark', 'abalone', 'acme', 'add', 'aerate']
>>>x.sort(key=len)
>>> x
['add', 'acme','aerate', 'abalone', 'arrdvark']
>>> x =
>>>x.sort(reverse=True)
>>> x
元组:不可变序列,圆括号括起来,内部使用逗号分隔
空元组:()
一个值的元组:(42,) ,即使只有一个值,必须加上逗号
tuple函数:以一个序列作为参数并把它转换为元组
>>>tuple()
(1, 2, 3)
页:
[1]