首先申明下,本文为笔者学习《Python学习手册》的笔记,并加入笔者自己的理解和归纳总结。
列表是有序集合对象类型,列表可以包含任何种类的对象:数字、字符串甚至其他列表。
1. 列表定义中括号[]直接定义列表。
>>> L = [] # 空列表 >>> L = [1, 2, 3, 4] # 整型列表 >>> L = [1, 1.23, "helloworld"] # 列表可以包含任何种类对象
list()可以生成列表。
>>> list("helloworld") # list把字符串生成字符列表
['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
range()生成连续整数列表。
>>> range(1, 10) # range产生一个1到9的数字列表 [1, 2, 3, 4, 5, 6, 7, 8, 9]2. 列表一般操作
>>> [1, 2, 3] + [4, 5, 6] # 加号合并两个列表 [1, 2, 3, 4, 5, 6] >>> ["hello", "world"] * 3 # 乘号使列表重复合并 ['hello', 'world', 'hello', 'world', 'hello', 'world'] >>> L = [1, 2, 3, 4] # len()查询列表长度 >>> len(L) 4 >>> for x in L: # for遍历列表 print x, 1 2 3 4 >>> X = [x ** 2 for x in L] # for直接生成一个列表 >>> X [1, 4, 9, 16] >>> 2 in L # in查询一个对象是否在列表中 True >>> 5 in L False3. 索引和分片
列表支持索引访问,也可以使用分片来获取部分列表。
>>> L = [1, 2, 3, 4, 5] >>> L[2] # []通过索引访问 3 >>> L[1:3] # 分片访问,从索引1到索引3 [2, 3] >>> L[1:] # 分片访问,从索引1到最后 [2, 3, 4, 5]
如果列表的元素是新的列表,同样可以使用索引访问。
>>> matrix=[[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> matrix[1] # matrix的某个元素是列表 [4, 5, 6] >>> matrix[1][1] # 连续通过[]访问 5
索引赋值和分片赋值。
>>> L = [1, 2, 3, 4, 5] >>> L[2] = 6 # 列表通过[]赋值 >>> L [1, 2, 6, 4, 5] >>> L[1:3] = [7, 8, 9] # 分片赋值,在索引1到索引3之间赋值 >>> L # 列表原有的值[2, 6]被替代为[7, 8, 9] [1, 7, 8, 9, 4, 5]4. 列表方法
添加和删除
>>> L = ["Hello", "World!"]
>>> L.append("Welcome") # append方法在列表末端添加元素
>>> L
['Hello', 'World!', 'Welcome']
>>> L.extend(["to", "Python"]) # extend方法在列表末端插入多个元素
>>> L
['Hello', 'World!', 'Welcome', 'to', 'Python']
>>> L.pop() # pop方法删除列表末端元素。
'Python'
通过索引添加、删除。
>>> L = ["Hello", "World!", "Welcome", "to", "Python"]
>>> L.index("World!") # index方法查询索引,如果找不到会报错
1
>>> "World!" in L # 在index方法调用前最好先查询
True
>>> L.insert(1, "OK") # 在索引1的位置插入字符串
>>> L
['Hello', 'OK', 'World!', 'Welcome', 'to', 'Python']
>>> L.pop(3) # pop方法中传入索引,删除指定值
'Welcome'
>>> L
['Hello', 'OK', 'World!', 'to', 'Python']
删除指定值
>>> L = ["Hello", "World!", "Welcome", "to", "Python"]
>>> L.remove("World!") # remove方法删除指定值
>>> L
['Hello', 'Welcome', 'to', 'Python']
>>> L = [1, 2, 3, 4, 5]
>>> L.remove(2) # remove方法删除指定值2
>>> L
[1, 3, 4, 5]
排序
>>> L = ["Hello", "World!", "Welcome", "to", "Python"] >>> L.sort() # sort方法对列表进行排序 >>> L ['Hello', 'Python', 'Welcome', 'World!', 'to'] >>> L.sort(key=str.lower, reverse=True) # 修改排序行为 >>> L ['World!', 'Welcome', 'to', 'Python', 'Hello']
反转列表。
>>> L = [1, 3, 5, 2, 4, 6] >>> L.reverse() >>> L [6, 4, 2, 5, 3, 1]5. 内置函数
del函数
>>> L = ["Hello", "World!", "Welcome", "to", "Python"] >>> del L[1] # 删除单个序列 >>> L ['Hello', 'Welcome', 'to', 'Python'] >>> del L[2:] # 删除多个序列 >>> L ['Hello', 'Welcome']
sorted函数
>>> L = ["Hello", "World!", "Welcome", "to", "Python"] >>> sorted(L) # 对列表排序 ['Hello', 'Python', 'Welcome', 'World!', 'to'] >>> sorted(L, key=str.lower) # 指定规则对列表排序 ['Hello', 'Python', 'to', 'Welcome', 'World!']
相关文章
Python 数字类型
Python 布尔型
Python 字符串
Python 列表
Python 字典
Python 元组
Python 集合
Python 变量和作用域
Python 语句
Python 函数
Python 类



