2.1 列表的创建与操作 / Creating and Manipulating Lists
中文 :列表是有序可变序列,用方括号创建。索引从 0 开始,负数索引从末尾倒数。
English: Lists are ordered, mutable sequences created with square brackets. Indexing starts at 0; negative indices count from the end.
python
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple 第一个 / first
print(fruits[-1]) # cherry 最后一个 / last
print(fruits[1:3]) # ['banana', 'cherry'] 切片 / slicing
fruits.append("date") # 末尾添加 / append at end
fruits.insert(1, "blueberry") # 指定位置插入 / insert at index
fruits.remove("banana") # 按值删除 / remove by value
last = fruits.pop() # 弹出末尾 / pop last
print(fruits) # ['apple', 'blueberry', 'cherry']
print(last) # date
2.2 列表推导式 / List Comprehensions
中文 :列表推导式用一行代码生成列表,语法为 [表达式 for 元素 in 可迭代对象 if 条件]。
English : A list comprehension builds a list in one line: [expression for item in iterable if condition].
python
numbers = [1, 2, 3, 4, 5, 6]
# 每个元素平方 / square each element
squares = [n ** 2 for n in numbers]
print(squares) # [1, 4, 9, 16, 25, 36]
# 只保留偶数 / keep only even numbers
evens = [n for n in numbers if n % 2 == 0]
print(evens) # [2, 4, 6]
# 带条件表达式 / with conditional expression
labels = ["偶 / even" if n % 2 == 0 else "奇 / odd" for n in numbers]
print(labels)
2.3 字典的创建与遍历 / Creating and Iterating Dictionaries
中文 :字典存储键值对,键必须可哈希且唯一。用 get() 访问不存在的键可返回默认值,避免 KeyError。
English : Dictionaries store key-value pairs. Keys must be hashable and unique. Use get() to avoid KeyError when a key may be missing.
python
student = {
"name": "Alice",
"age": 20,
"major": "Computer Science"
}
print(student["name"]) # Alice
print(student.get("gpa", "N/A")) # N/A 默认值 / default
student["gpa"] = 3.8 # 新增键 / add key
student["age"] = 21 # 修改值 / update value
# 遍历 / iteration
for key, value in student.items():
print(f"{key}: {value}")
# 只遍历键 / iterate keys only
print(list(student.keys()))
2.4 条件判断 / Conditional Statements
中文 :elif 是 else if 的缩写。Python 用缩进表示代码块,通常为 4 个空格。
English : elif is short for else-if. Python uses indentation (typically 4 spaces) to define blocks.
python
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "D"
print(f"分数 / Score: {score}, 等级 / Grade: {grade}")
2.5 循环 / Loops
中文 :for 用于遍历可迭代对象,while 在条件为真时重复执行。break 跳出循环,continue 跳过本次迭代。
English : for iterates over an iterable; while repeats while a condition is true. break exits the loop; continue skips the current iteration.
python
# for 循环 / for loop
for i in range(1, 6): # 1 到 5 / 1 to 5
if i == 3:
continue # 跳过 3 / skip 3
print(i, end=" ")
print() # 1 2 4 5
# while 循环 / while loop
count = 0
while count < 3:
print(f"count = {count}")
count += 1
# 带 else 的循环 / loop with else
for n in [2, 4, 6]:
if n % 2 != 0:
print("发现奇数 / found odd")
break
else:
print("全部是偶数 / all even")
2.6 练习 / Exercise
中文 :统计一段文本中每个单词出现的次数,按次数降序输出前 3 个。
English: Count word frequencies in a text and print the top 3 in descending order.
python
text = "the quick brown fox jumps over the lazy dog the fox"
words = text.split()
counter = {}
for word in words:
counter[word] = counter.get(word, 0) + 1
# 按次数降序排序 / sort by count descending
top3 = sorted(counter.items(), key=lambda x: x[1], reverse=True)[:3]
for word, count in top3:
print(f"{word}: {count}")