学习python官网 5. Data Structures 5.1. More on Lists— Python 3.13.3 documentation后,可以做这部分练习题。
练习题
练习题1:基础操作填空
创建一个空列表lst,使用______方法在末尾添加数字5。
使用______方法将元组(1,2)和集合{3,4}的元素依次添加进lst。
使用______方法在索引2的位置插入字符串"hello"。
用______方法删除第一个遇到的数字4,若不存在不报错的方法是______。
反转列表应使用______方法,返回排序后新列表的关键字参数是______。
练习题2:代码补全
补全代码实现以下功能:
colors = ["red", "blue"]
# 在blue后面插入"green"
colors.______(2, "green")
# 添加元组("purple","pink")的所有元素
colors.______(______)
# 删除"red"并打印被删元素
print(colors.______(0))
# 清空列表
colors.______()
练习题3:错误分析与改错
找出下面代码的错误并修正:
lst = [5, 2, 8, 2]
print(lst.index(2, 2, 5)) # 错误1
lst.remove(3) # 错误2
lst.pop(4) # 错误3
lst.extend(123) # 错误4
lst = lst.append(9) # 错误5
练习题4:结果预测
写出以下代码的输出:
a = [3, 1, 4, 1, 5]
b = a.copy()
a.insert(2, 6)
a.remove(1)
print(a.index(1))
print(a.count(1))
b.sort(reverse=True)
print(b)
a.reverse()
print(a + b)
练习题5:综合编程
编写函数处理列表:
接收包含重复元素的列表
删除所有偶数索引的元素(0,2,4…)
在剩余元素前插入他们的出现次数
返回处理后的列表降序排列
示例:输入[5,2,5,3] → 输出[3, 2, 1, 1]
答案
练习题1答案
lst.append(5)
lst.extend() → 分别写lst.extend((1,2))和lst.extend({3,4})
lst.insert(2, "hello")
lst.remove(4) 或者 lst.pop(lst.index(4)) ,if 4 in lst: lst.remove(4)
reverse();key
练习题2答案
colors.insert(2, "green")
colors.extend(("purple","pink"))
print(colors.pop(0))
colors.clear()
练习题3答案
错误1:查找范围5超过列表长度4 → 改为lst.index(2,2,4)
错误2:列表没有3 → 先if 3 in lst: lst.remove(3)
错误3:索引越界 → 最大索引3
错误4:数字不是可迭代对象 → 改为[123]或转成字符串
错误5:append()返回None → 分开写 lst.append(9)
练习题4答案
输出:
3
1
[5, 4, 3, 1, 1]
[5, 1, 4, 6, 3, 5, 4, 3, 1, 1]
练习题5答案
def process_list(lst):
# 删除偶数索引(保留奇数索引)
new_lst = [lst[i] for i in range(1, len(lst), 2)]
# 统计出现次数并插入
result = []
for num in new_lst:
count = new_lst.count(num)
result.extend([count, num])
# 降序排列
result.sort(reverse=True)
return result
验证示例:
输入[5,2,5,3] → 保留索引1,3 → [2,3]
统计插入后 → [1,2, 1,3]
降序 → [3,2,1,1] → 需要调整逻辑(可能需要统计全局次数)
更准确的实现:
def process_list(lst):
# 步骤1:删除偶数索引
filtered = [lst[i] for i in range(len(lst)) if i%2 != 0]
# 步骤2:插入出现次数
result = []
for num in filtered:
cnt = filtered.count(num)
result.append(cnt)
result.append(num)
# 步骤3:降序排序
result.sort(reverse=True)
return result
这样输入[5,2,5,3] → 过滤后[2,3] → 插入次数[1,2,1,3] → 排序后[3,2,1,1] → 需要根据示例调整逻辑(可能需要保持插入顺序的统计)
最终正确答案需保持元素对:
def process_list(lst):
filtered = lst[1::2] # 更简洁的切片写法
counted = [[filtered.count(x), x] for x in filtered]
# 扁平化列表
result = [item for pair in counted for item in pair]
result.sort(reverse=True)
return result
# 示例输入输出:
# [5,2,5,3] → filtered [2,3]
# counted → [[1,2], [1,3]]
# result → [1,2,1,3] → 排序后 [3,2,1,1]
Python官网list方法练习题及答案
709

被折叠的 条评论
为什么被折叠?



