如何定义
- 用[]定义一个list,list中的不同元素用,分割,元素可变,可以容纳python的任何对象
- list()强制转换
>>> list1 = ['I','am',18,'year','old','.']
>>> print(list1)
['I', 'am', 18, 'year', 'old', '.']
>>>
>>> list()
[]
>>> list('123')
['1', '2', '3']
>>>
访问列表中元素
- 用索引值访问
正序从0开始,倒序从-1开始,不能访问索引值不存在的值
>>> list1 = ['I','am',18,'year','old','.']
>>> list1[0]
'I'
>>> list1[-2]
'old'
>>> list1[-7]
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
list1[-7]
IndexError: list index out of range
>>>
- 切片访问
list[开始:结束:步长]开始为空表示从第一个元素开始,结束为空表示到最后一个元素,步长不能为0
list1[0:2] 左闭右开,取list[0],list[1]
list1[:] 正序列表
list1[::-2] 反序,按步长2取值
列表内置方法
L.append(object) -> None -- append object to end
L.clear() -> None -- remove all items from L
L.copy() -> list -- a shallow copy of L
L.count(value) -> integer -- return number of occurrences of value
L.extend(iterable) -> None -- extend list by appending elements from the iterable
L.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
L.insert(index, object) -- insert object before index
L.pop([index]) -> item -- remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
L.remove(value) -> None -- remove first occurrence of value.
Raises ValueError if the value is not present.
L.reverse() -- reverse *IN PLACE* #翻转
L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
#进行排序的元素类型要一致,否则出错
常用函数
max、min中的对象元素要一致
>>> max(lis1)
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
max(lis1)
TypeError: '>' not supported between instances of 'str' and 'int'
列表特殊操作
- 列表组合
拼接+ - 列表的乘法
与数字X表示,重复列表元素X次 - 判断元素是否在列表内部
in
not in - 迭代列表中的每个元素
>>> a = [1,2]
>>> a*3
[1, 2, 1, 2, 1, 2]
>>> a + a
[1, 2, 1, 2]
>>> 1 in a
True
>>> for i in a:
print(i)
1
2
列表增删改查
增append(),insert()
列表末尾插入
索引正序从0开始,倒序从-1开始
list1[0:0] =[‘you’] 表示在开头插入字符串you
删pop()、remove()、del list[0]
pop()默认删列表最后一个元素,可以指定索引值删除指定位置元素,对应索引值不存在则报错
remove()删除列表中对应的元素,value参数不存在会报错
还有一种用del方法删除
del list1[1:4] 表示删除列表list1中第2-4对应的元素
改
利用索引值直接修改
fruit = ['lizi', 'pineapple', 'pear']
fruit[0]='pingguo'
fruit[0:2]=['apple']
查
关键字列表
l = [‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]
索引查询和切片查询
嵌套查询,如果一个列表中又有列表或字典等,可以用嵌套查询
list[0][2] 诸如此类