笔记是本人学习时为方便以后复习所作,原教程链接 Python3 教程 | 菜鸟教程
访问列表
list = ['hello',2020,'world',26,True,'string']
print(list[0])
print(list[1:5]) #截取列表
运行结果
hello
[2020, ‘world’, 26, True]
更新列表
list = ['hello',2020,'world',26,True,'string']
print(list[0])
list[0] = 12
print(list[0])
运行结果
hello
12
删除列表元素
list = ['hello',2020,'world',26,True,'string']
print(list)
del list[1:3]
print(list)
运行结果
[‘hello’, 2020, ‘world’, 26, True, ‘string’]
[‘hello’, 26, True, ‘string’]
脚本操作符
- + —用于组合列表
- * —用于重复列表
list1 = [1,2,3]
list2 = [4,5,6]
list = list1 + list2 #列表组合
print(list)
print(len(list)) #列表长度
print(list1 * 2) #列表重复
print(3 in list) #判断元素是否在列表中
print(3 not in list)
x = 1
for x in list: #遍历
print(x,end='')
运行结果
[1, 2, 3, 4, 5, 6]
6
[1, 2, 3, 1, 2, 3]
True
False
123456
列表嵌套
list1 = [1,2,3]
list2 = [4,5,6]
list = [list1,list2]
print(list)
print(list[1])
print(list[0][1])
运行结果
[[1, 2, 3], [4, 5, 6]]
[4, 5, 6]
2
列表函数&方法
序号 | 函数 | 作用 |
---|---|---|
1 | len(list) | 列表元素个数 |
2 | max(list) | 返回列表元素最大值 |
3 | min(list) | 返回列表元素最小值 |
4 | list(seq) | 将元组转换为列表 |
list1 = [1,4,2,5]
print(len(list1))
print(max(list1))
print(min(list1))
'''
list()方法用于将元组或字符串转换为列表
格式:list(seq)
seq---要转换为列表的元组或字符串
'''
str = 'boy'
list2 = list(str)
print(list2)
a_Tuple = ('hello',1,2,'china')
list3 = list(a_Tuple)
print(list3)
运行结果
4
5
1
[‘b’, ‘o’, ‘y’]
[‘hello’, 1, 2, ‘china’]
序号 | 方法 | 作用 |
---|---|---|
1 | list.append(obj) | 在列表末尾添加新的对象 |
2 | list.count(obj) | 统计某个元素在列表中出现的次数 |
3 | list.extend(seq) | 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) |
4 | list.index(obj) | 从列表中找出某个值第一个匹配项的索引位置 |
5 | list.insert(index, obj) | 将对象插入列表 |
6 | list.pop([index=-1]) | 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 |
7 | list.remove(obj) | 移除列表中某个值的第一个匹配项 |
8 | list.reverse() | 反向列表中元素 |
9 | list.sort( key=None, reverse=False) | 对原列表进行排序 |
10 | list.clear() | 清空列表 |
11 | list.copy() | 复制列表 |
list = [1,4,2,5,4]
#1
list.append(9)
print(list)
#2
print(list.count(4))
#3
'''list.extend(seq)
seq -- 元素列表,可以是列表、元组、集合、字典,若为字典,则仅会将键(key)作为元素依次添加至原列表的末尾
'''
list3 = [1,2,3,4,5]
str = 'china'
list3.extend(str)
print(list3)
#4
print(list.index(5))
#5
list.insert(2,'hello')
print(list)
#6
print(list.pop(5))
print(list)
#7
list.remove(2)
print(list)
#8
list.reverse()
print(list)
#9
list1 = [3,2,6,4,8]
list1.sort()
print(list1) #升序
list1.sort(reverse=True)
print(list1) #降序
#10
list1.clear()
print(list1)
#11
list2 = list.copy()
print(list2)
运行结果
[1, 4, 2, 5, 4, 9]
2
[1, 2, 3, 4, 5, ‘c’, ‘h’, ‘i’, ‘n’, ‘a’]
3
[1, 4, ‘hello’, 2, 5, 4, 9]
4
[1, 4, ‘hello’, 2, 5, 9]
[1, 4, ‘hello’, 5, 9]
[9, 5, ‘hello’, 4, 1]
[2, 3, 4, 6, 8]
[8, 6, 4, 3, 2]
[]
[9, 5, ‘hello’, 4, 1]