第二篇:列表、字典与流程控制 / 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

相关推荐
呉師傅1 小时前
Win7剪切文件变成复制文件如何修改【资源管理器异常类故障】
运维·网络·windows·电脑
略略略咯咯1 小时前
33333
开发语言·windows·python
2501_915918412 小时前
Windows 上开发 React Native iOS,真机调试、Fast Refresh 与打包 ipa
windows·vscode·react native·ios·个人开发·swift·敏捷流程
LannyChung16 小时前
PowerShell 下 git log 中文乱码的完整排查与解决
windows·git
谙弆悕博士21 小时前
用 C 写了个 Windows 聊天室,踩了几个多线程和控制台的坑
c语言·开发语言·c++·windows·网络编程·聊天室
Data-Miner1 天前
一个省大模型积分的 Excel 数据处理方案:脱敏生成逻辑,脚本复用把 token 降到 0
人工智能·windows·excel
无巧不成书02181 天前
Tomcat部署JSP文件完整指南:手动部署+IDEA工程化实现 附404访问错误全排查
java·ide·windows·tomcat·intellij-idea·js
张张的快乐时光呀!1 天前
如何配置CUDA开发环境?
windows
fatCatLA1 天前
记一次狼狈的装机
windows