【Python第二章】2.10题
# 列表对象的常用方法
list1 = [1, 2, 3, 4, 5, 6, 8, 84, 456, 4, 6468, 41, 1, 123, 4]
abclist = ["a", "b", "v", "d", "s", "f", "g", "h", "b", "c"]
# 1.list.append
# list.append() 在列表后面插入对象
print(list1)
print("---------------------------")
# list.insert(下标,插入对象)
list1.insert(2, 123)
print(list1)
print("---------------------------")
# list.extend(可迭代对象追加到当前列表)
list1.extend("OK")
print(list1)
print("---------------------------")
# list.index(查找值) 找到返回下标 找不到报错
print(list1.index(456))
print("---------------------------")
# list.count(对象) 查找对象出现的次数
print(list1.count(1))
print("---------------------------")
# list.remove(对象) 删除匹配的对象并返回删除后的列表
print(list1.remove(123))
print("---------------------------")
# list.pop(下标) 删除并返回下标指定对象,默认删除并返回末段对象,若列表为空则报错
print(list1.pop(0))
print("---------------------------")
# list.sort(reverse=True) 默认将列表降序排列
abclist.sort()
print(abclist)
print("---------------------------")
# list.copy() 浅拷贝列表
clist = list1.copy()
print(clist)
print("---------------------------")
# list.clear() 清空列表
clist.clear()
print(clist)
print("---------------------------")
运行结果:
[1, 2, 3, 4, 5, 6, 8, 84, 456, 4, 6468, 41, 1, 123, 4]
---------------------------
[1, 2, 123, 3, 4, 5, 6, 8, 84, 456, 4, 6468, 41, 1, 123, 4]
---------------------------
[1, 2, 123, 3, 4, 5, 6, 8, 84, 456, 4, 6468, 41, 1, 123, 4, 'O', 'K']
---------------------------
9
---------------------------
2
---------------------------
None
---------------------------
1
---------------------------
['a', 'b', 'b', 'c', 'd', 'f', 'g', 'h', 's', 'v']
---------------------------
[2, 3, 4, 5, 6, 8, 84, 456, 4, 6468, 41, 1, 123, 4, 'O', 'K']
---------------------------
[]
---------------------------
Views: 412