第二篇:列表、字典与流程控制 / Lists, Dictionaries & Control Flow

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}")

https://github.com/0voice

相关推荐
xx z19 小时前
directx修复工具下载(DirectX Repair 增强版 使用说明)
windows·系统·工具·软件
xx z21 小时前
pcl2启动器下载(Minecraft PCL2 启动器 最新版 安装与使用说明)
windows·游戏·工具·软件
凯瑟琳.奥古斯特1 天前
我开源了一个 Windows 截图取字工具:全局热键 + 离线 OCR + 标注打码,不上传任何数据
windows·ocr
Funlang2 天前
在 Windows 95 上跑 Fun
windows
ö Constancy2 天前
一台电脑的硬件组成与作用:按功能分类详解(Windows 与 Linux 视角)
linux·windows·电脑
雪落漂泊3 天前
Liunux进程(七):程序控制篇(中)
linux·运维·windows
承渊政道4 天前
Fooocus本地AI绘图教程:Windows部署、低门槛生图与远程访问
人工智能·windows·cpolar·fooocus·生图
陈工大模型4 天前
收到乱码压缩包之后,我重新测了 7-Zip、Bandizip 和win解压缩
windows·电脑·软件工程·软件需求·7-zip
谙弆悕博士4 天前
在文件夹右键直接打开 Kali WSL:一条 `wsl --cd` 注册表脚本
windows·脚本·wsl·右击·ksli
陈工大模型4 天前
解压工具的三个技术分水岭:编码、分卷、容器格式
人工智能·windows·安全·解压工具·免费国内办公软件