列表概述
序列是Python中最基本的数据结构。序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。
Python有6个序列的内置类型,但最常见的是列表和元组。
序列都可以进行的操作包括索引,切片,加,乘,检查成员。
此外,Python已经内置确定序列的长度以及确定最大和最小的元素的方法。
列表是最常用的Python数据类型,它可以作为一个方括号内的逗号分隔值出现。
列表的数据项不需要具有相同的类型
创建一个列表,只要把逗号分隔的不同的数据项使用方括号括起来即可。
访问列表中的值
序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。
例:list1 = [ 'a','great','movie','the Charlie Brown and snoopy show',221,345,667,998];
list1[2]# 获取列表中的第3个元素
>>> #examble#一个案例表述列表的操作
包含访问列表中的值、删除列表中的元素、更新列表、拼接、嵌套、判定等
>>> a = ['this','is',"snoopy's",'list','4','33','666']>>> a[5]#输出列表a的第六项元素
'33'
>>> del a[7]
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
del a[7]
IndexError: list assignment index out of range 错误原因:列表并不存在第8个元素
>>> del a[5]#删除列表中的第6个元素
>>> a
['this', 'is', "snoopy's", 'list', '4', '666']
>>> a.append(29)#列表函数,将 29加入列表,默认在末尾(可设置位置)
>>> a
['this', 'is', "snoopy's", 'list', '4', '666', 29]
>>> a + ['so','easy','hahahahahaha',999]#列表加法,直接加入到列表之后
['this', 'is', "snoopy's", 'list', '4', '666', 29, 'so', 'easy', 'hahahahahaha', 999]
>>> max(a)
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
max(a)
TypeError: '>' not supported between instances of 'int' and 'str' 错误原因:整型和字符串不能比较大小
>>> len(a)#函数之列表的长度
7
>>> b = (1,2,3,4,5)
>>> c = ('a','b','c','d','e')
>>> d = (b,c)#嵌套列表
>>> d
((1, 2, 3, 4, 5), ('a', 'b', 'c', 'd', 'e'))
>>> m = (a,b)
>>> m
(['this', 'is', "snoopy's", 'list', '4', '666', 29], (1, 2, 3, 4, 5))
>>> 1 in b#判定
True
Python列表常用函数
序号 | 函数 |
---|---|
1 | len(list) 列表元素个数 |
2 | max(list) 返回列表元素最大值 |
3 | min(list) 返回列表元素最小值 |
4 | list(seq) 将元组转换为列表 |
Python包含以下方法:
序号 | 方法 |
---|---|
1 | list.append(obj) 在列表末尾添加新的对象 |
2 | list.count(obj) 统计某个元素在列表中出现的次数 |
3 | list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) |
4 | list.index(obj) 从列表中找出某个值第一个匹配项的索引位置 |
5 | list.insert(index, obj) 将对象插入列表 |
6 | list.pop(obj=list[-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 |
7 | list.remove(obj) 移除列表中某个值的第一个匹配项 |
8 | list.reverse() 反向列表中元素 |
9 | list.sort([func]) 对原列表进行排序 |
10 | list.clear() 清空列表 |
11 | list.copy() 复制列表 |