第三章练习答案
00-objects-and-mutability
练习 1:预测输出
python
x = [1, 2]
y = [1, 2]
z = x
print(x == y, x is y, x is z) # True False True练习 2:别名陷阱
python
def append_twice(item, lst):
lst = lst.copy() # 创建副本
lst.append(item)
lst.append(item)
return lst
numbers = [1, 2, 3]
result = append_twice(4, numbers)
print(numbers) # [1, 2, 3]
print(result) # [1, 2, 3, 4, 4]练习 3:浅拷贝问题
python
# 正确写法
matrix = [[0] * 3 for _ in range(3)]
matrix[0][0] = 1
print(matrix) # [[1, 0, 0], [0, 0, 0], [0, 0, 0]]
# 错误写法
bad_matrix = [[0] * 3] * 3 # 3个引用指向同一个列表
bad_matrix[0][0] = 1
print(bad_matrix) # [[1, 0, 0], [1, 0, 0], [1, 0, 0]]01-lists-and-tuples
练习 1:切片操作
python
lst = [0,1,2,3,4,5,6,7,8,9]
print(lst[::2]) # [0, 2, 4, 6, 8](偶数索引)
print(lst[-3:]) # [7, 8, 9](倒数3个)
print(lst[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0](反转)练习 2:列表推导式
python
squares = [x**2 for x in range(1, 101)]
divisible = [x for x in range(1, 101) if x % 3 == 0 or x % 5 == 0]
lengths = [len(s) for s in ['hello', 'world', 'python']]02-dicts-and-sets
练习 1:词频统计
python
def word_count(text):
words = text.lower().split()
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
return freq
# 或用Counter
from collections import Counter
def word_count(text):
return Counter(text.lower().split())练习 2:字典合并
python
def merge_dicts(d1, d2):
return {**d1, **d2}03-strings-and-unicode
练习 1:字符串反转
python
def reverse_string(s):
return s[::-1]练习 5:回文判断
python
def is_palindrome(s):
s = s.lower().replace(' ', '')
return s == s[::-1]06-datetime-and-timezone
练习 1:计算天数差
python
from datetime import datetime
def days_between(date1, date2):
d1 = datetime.strptime(date1, '%Y-%m-%d')
d2 = datetime.strptime(date2, '%Y-%m-%d')
return abs((d2 - d1).days)07-json-and-serialization
练习 1:配置文件
python
import json
config = {'host': 'localhost', 'port': 8080}
# 保存
with open('config.json', 'w') as f:
json.dump(config, f, indent=2)
# 读取
with open('config.json', 'r') as f:
loaded = json.load(f)回到第三章概览 · 返回Python学习路线