list1 = [1,2,3,4,5,6,7,8,9]
>>> list1[1:5]
[2, 3, 4, 5]
>>> list[1:5:2]
>>> list1[1:5:2]
[2, 4]
# 反转列表
>>> list1[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
# + 和 *
>>> list1 = [1,2,3]
>>> list2 = [4,5,6]
>>> list1 + list2 # 两个列表相加
[1, 2, 3, 4, 5, 6]
>>> list1 * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
# in 和 not in
>>> list1 = [1,2,3,4,5,6]
>>> 1 in list1 # 1 是否在list1中
True
>>> 7 in list1
False
>>> 1 not in list1 # 1 是否不在list1中
False
>>> 7 not in list1
True
# len()
>>> list1 = [1,2,3,4,5,6]
>>> len(list1) # 获取list列表中元素的个数
6
# max()和min()
>>> max(list1)
6
>>> min(list1)
1
# list.index(x[, start[, end]])
>>> list1 = [1,2,3,4,5,6,7,8,9]
>>> list1.index(2)
1
>>> list1.index(9)
8
>>> list1 = ['hello', 'python', 'world']
>>> list1.index('hello')
0
>>> list1.index('python')
1
>>> list1.index('hello', 1, 2) # 查找不到,则抛出ValueError异常
Traceback (most recent call last):
File "", line 1, in <module>
ValueError: 'hello' is not in list
# list.count(x)
>>> list1 = [1,1,2,3,4,4,4,5,6]
>>> list1.count(1)
2
>>> list1.count(4)
3
>>> list1.count(10) # 10不存在于列表,则出现0次
0
>>> list1 = [1,2,3,4,5,6]
>>> list1[1:3] = ['a','b','c','d']
[1, 'a', 'b', 'c', 'd', 4, 5, 6]
# 指定步长
>>> list1 = [1,2,3,4,5,6]
>>> list1[1:5:2] = ['a','b']
>>> list1
[1, 'a', 3, 'b', 5, 6]
# 指定步长 如果序列中元素的个数和切片中元素的个数不一致
# 则会抛出 ValueError 异常
>>> list1[1:5:2] = ['a','b','c']
Traceback (most recent call last):
File "", line 1, in <module>
ValueError: attempt to assign sequence of size 3 to extended slice of size 2
>>> list1 = [1,2,3,4,5,6]
>>> del list1[1] # 删除列表中索引为1的元素
[1, 3, 4, 5, 6]
>>> del list1[1:3] # 删除索引为1到索引为3(不包含)的元素
>>> list1
[1, 5, 6]
# 如果索引超过列表,则抛出IndexError异常
>>> del list1[10]
Traceback (most recent call last):
File "", line 1, in <module>
IndexError: list assignment index out of range
>>> list1 = [1,2,3,4]
>>> list1.append(5)
[1, 2, 3, 4, 5]
>>> list1 = [1,2,3,4]
>>> list1.insert(0,'a')
['a', 1, 2, 3, 4]
>>> list1.insert(3,'a')
['a', 1, 2, 'a', 3, 4]
>>> list1 = [1,2,3,4]
>>> list2 = [5,6,7]
>>> list1.extend(list2)
>>>> list1
[1, 2, 3, 4, 5, 6, 7]
>>> list1 = [1,2,3,4]
>>> list1.pop(1) # 删除索引为1的元素,并返回该元素
2
>>> list1
[1, 3, 4]
>>> list1 = [1,2,3,4]
>>> list1.remove(2) # 删除值为2的元素,非索引
>>> list1
[1, 3, 4]
>>> list1 = [1,2,3,4]
>>> list1.reverse() # 把列表顺序反转
>>> list1
[4, 3, 2, 1]
>>> list1 = [3,2,1,5,4,8,5,11,2,4]
>>> list1.sort() # 默认按照正序排列
>>> list1
[1, 2, 2, 3, 4, 4, 5, 5, 8, 11]
>>> list1 = [3,2,1,5,4,8,5,11,2,4]
>>> list1.sort(reverse=False) # 指定reverse=False按照倒序排列
>>> list1
[1, 2, 2, 3, 4, 4, 5, 5, 8, 11]
for 变量 in 序列(遍历的规则):
代码块
>>> list1 = [1,2,3,4,5]
>>> for i in list1:
... print(i)
1
2
3
4
5
参数说明
>>> for i in range(5):
... print(i)
...
0
1
2
3
4
>>> for i in range(1,5):
... print(i)
...
1
2
3
4
>>> for i in range(1,5,2):
... print(i)
...
1
3