3、列表list的常用方法
列表 list 的常用函数
cmp(list1, list2)
比较两个列表
返回值: -1:list1 < list2 0:list1 == list2 1:list1 > list2
示例 1:
list1 = [1, 2, 3, 4]
list2 = [1, 2, 3]
print(cmp(list1, list2)) # 输出:-1
示例 2:
list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(cmp(list1, list2)) # 输出:0
len(list)
:返回列表的长度
返回值:列表的长度
示例 1:
list1 = [1, 2, 3]
print(len(list1)) # 输出:3
max(list)
min(list) 返回列表中的最大值和最小值
返回值:列表中的最大值和最小值
示例 1:
list1 = [1, 2, 3, 4]
print(max(list1)) # 输出:4
示例 2:
list1 = [1, 2, 3, 4]
print(min(list1)) # 输出:1
list(seq)
将元组转换为列表
返回值:列表
示例 1:
tuple1 = (1, 2, 3, 4)
print(list(tuple1)) # 输出:[1, 2, 3, 4]
列表 list 的常用方法
list.append(element)
:在列表末尾添加一个新的元素
返回值:None
示例 1:
list1 = [1, 2, 3]
list1.append(4)
print(list1) # 输出:[1, 2, 3, 4]
list.insert(index, element)
:在指定位置插入一个元素
返回值:None
示例 1:
list1 = [1, 2, 3]
list1.insert(1, 4)
print(list1) # 输出:[1, 4, 2, 3]
list.extend(seq)
:在列表末尾添加多个元素
返回值:None
示例 1:
list1 = [1, 2, 3]
list1.extend([4, 5])
print(list1) # 输出:[1, 2, 3, 4, 5]
list.remove(element)
:删除列表中指定的元素
返回值:None
示例 1:
list1 = [1, 2, 3, 4]
list1.remove(3)
print(list1) # 输出:[1, 2, 4]
list.pop()
:删除列表中指定位置的元素,并返回该元素
返回值:删除的元素
示例 1:
list1 = [1, 2, 3, 4]
print(list1.pop(1)) # 输出:2
print(list1) # 输出:[1, 3, 4]
list.sort()
:对列表进行排序
返回值:None
示例 1:
list1 = [4,1,3,2]
list1.sort()
print(list1) # 输出:[1, 2, 3, 4]
list.reverse()
:对列表进行反转
返回值:None
示例 1:
list1 = [1, 2, 3, 4]
list1.reverse()
print(list1) # 输出:[4, 3, 2, 1]
list.count(element)
:返回列表中某个元素的个数
返回值:元素的个数
示例 1:
list1 = [1, 2, 3, 4, 1]
print(list1.count(1)) # 输出:2
list.index(element)
:返回列表中某个元素的索引
返回值:元素的索引
示例 1:
list1 = [1, 2, 3, 4, 1]
print(list1.index(1)) # 输出:0
list.copy()
:返回列表的浅拷贝
返回值:列表的浅拷贝
示例 1:
list1 = [1, 2, 3, 4]
list2 = list1.copy()
list2.append(5)
print(list1) # 输出:[1, 2, 3, 4]
print(list2) # 输出:[1, 2, 3, 4, 5]
list.clear()
:清空列表
返回值:None
示例 1:
list1 = [1, 2, 3, 4]
list1.clear()
print(list1) # 输出:[]