Python 快速上手:写给有编程基础的人

已经会其他语言,想快速掌握 Python 的语法特性和思维方式,这篇是捷径。

$1.6k 字/约 8 min👁— views

Python 快速上手:写给有编程基础的人

已经会 Java、Go、C++ 或者 JavaScript?这篇文章帮你用最短时间掌握 Python 的语法特性和思维方式,跳过基础概念,直接聚焦"和其他语言不一样的地方"。


Python vs 其他语言的关键区别

缩进即结构

Python 用缩进代替 {},不是风格问题,是语法要求:

if x > 0:
    print("positive")  # 必须缩进
    x -= 1
print("done")           # 在 if 外面

动态类型

x = 42        # int
x = "hello"   # 现在是 str,完全合法
x = [1, 2, 3] # 现在是 list

类型提示(type hints)是可选的,不影响运行时:

def greet(name: str) -> str:
    return f"Hello, {name}"

GIL(Global Interpreter Lock)

CPython 的多线程受 GIL 限制,CPU 密集型任务用 multiprocessingconcurrent.futures.ProcessPoolExecutor,IO 密集型用 asyncio 或线程。


变量与基础类型

# 基础类型
x: int = 42
pi: float = 3.14
name: str = "Alice"
flag: bool = True
nothing: None = None
data: bytes = b"hello"

# 类型转换
int("42")        # 42
float("3.14")    # 3.14
str(42)          # "42"
bool(0)          # False(0, "", [], {}, None 都是假值)
list("abc")      # ['a', 'b', 'c']

Python 的真假值(Falsy values)00.0""[]{}()set()NoneFalse


字符串操作

f-string(首选)

name = "World"
age = 25
print(f"Hello, {name}! Age: {age}")
print(f"{3.14159:.2f}")     # 格式化:3.14
print(f"{1000000:,}")       # 千分位:1,000,000
print(f"{'left':<10}|")     # 左对齐
print(f"{'right':>10}|")    # 右对齐

切片

s = "Hello, World!"
s[0]      # H
s[-1]     # !
s[7:]     # World!
s[:5]     # Hello
s[::2]    # Hlo ol!(每隔一个)
s[::-1]   # !dlroW ,olleH(反转)

常用方法

"  hello  ".strip()          # hello
"hello world".split()        # ['hello', 'world']
", ".join(["a", "b", "c"])   # a, b, c
"Hello".lower()              # hello
"hello".upper()              # HELLO
"hello world".replace("o", "0")  # hell0 w0rld
"hello".startswith("he")    # True
"hello".find("ll")           # 2

列表

nums = [1, 2, 3, 4, 5]

# 切片
nums[1:3]    # [2, 3]
nums[::-1]   # [5, 4, 3, 2, 1]

# 常用方法
nums.append(6)           # 尾部追加,O(1)
nums.extend([7, 8])      # 追加多个
nums.insert(0, 0)        # 头部插入,O(n) 慎用
nums.pop()               # 移除尾部,O(1)
nums.pop(0)              # 移除头部,O(n) 慎用
nums.remove(3)           # 移除第一个值为 3 的元素
nums.index(4)            # 找到元素的下标
nums.sort()              # 原地排序
sorted(nums)             # 返回新列表
nums.sort(reverse=True)  # 降序
nums.sort(key=lambda x: -x)  # 自定义排序

列表推导式

# 基础
squares = [x**2 for x in range(10)]

# 带条件
evens = [x for x in range(20) if x % 2 == 0]

# 双重循环
pairs = [(x, y) for x in [1,2,3] for y in [4,5,6]]

# 对比 Java:
# List<Integer> squares = IntStream.range(0, 10)
#     .map(x -> x * x).boxed().collect(Collectors.toList());

字典

d = {"name": "Alice", "age": 25}

# 访问
d["name"]           # Alice,不存在时 KeyError
d.get("email")      # None,不存在时返回 None
d.get("email", "")  # 指定默认值

# 修改
d["city"] = "Beijing"
d.update({"age": 26, "job": "dev"})

# 遍历
for k, v in d.items():
    print(f"{k}: {v}")

# 字典推导式
squared = {k: v**2 for k, v in {"a": 1, "b": 2}.items()}

# 合并(Python 3.9+)
merged = {"a": 1} | {"b": 2}   # {'a': 1, 'b': 2}
d1 = {"a": 1}
d1 |= {"b": 2}                  # 原地合并

# 旧方法(兼容 3.8)
merged = {**d1, **d2}

元组

point = (3, 4)
x, y = point          # 解包
a, *rest = (1, 2, 3, 4)  # a=1, rest=[2, 3, 4]

# 元组可作 dict key(不可变)
cache = {}
cache[(0, 0)] = "origin"

# 单元素元组
single = (42,)   # 注意逗号!(42) 只是括号,不是元组

# namedtuple(结构化)
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y)  # 3 4

集合

s1 = {1, 2, 3, 4}
s2 = {3, 4, 5, 6}

s1 & s2    # 交集:{3, 4}
s1 | s2    # 并集:{1, 2, 3, 4, 5, 6}
s1 - s2    # 差集:{1, 2}
s1 ^ s2    # 对称差:{1, 2, 5, 6}

# 去重
unique = list(set([1, 2, 2, 3, 3, 3]))  # [1, 2, 3]

# 成员检测 O(1)
print(3 in s1)   # True

# frozenset(不可变,可作 dict key)
fs = frozenset([1, 2, 3])

条件与循环

# 三元表达式(类比 Java/JS 的 ? :)
result = "yes" if condition else "no"

# for-else(Python 特有!其他语言没有)
for item in items:
    if item == target:
        break
else:
    # 只有循环正常结束(没有 break)才执行
    print("not found")

# enumerate(带下标的 for)
for i, v in enumerate(["a", "b", "c"]):
    print(i, v)  # 0 a / 1 b / 2 c

# zip(同步遍历多个序列)
for a, b in zip([1, 2, 3], ["x", "y", "z"]):
    print(a, b)

函数

# 默认参数
def connect(host, port=5432, timeout=30):
    pass

# 关键字参数(顺序无关)
connect(host="localhost", timeout=10, port=3306)

# *args 和 **kwargs
def log(*args, **kwargs):
    print(args)    # tuple
    print(kwargs)  # dict

log(1, 2, 3, level="info", tag="debug")

# 仅关键字参数(* 之后的参数)
def func(a, b, *, key_only):
    pass
func(1, 2, key_only=3)   # OK

# lambda(适合简单的一次性函数)
square = lambda x: x**2
nums.sort(key=lambda x: x[1])   # 按第二个元素排序

解包技巧

# 交换变量(Python 独有的优雅)
a, b = b, a

# 扩展解包
first, *middle, last = [1, 2, 3, 4, 5]
# first=1, middle=[2,3,4], last=5

# _ 作占位符
_, important, _ = (1, 2, 3)

# 函数参数解包
args = (1, 2, 3)
func(*args)          # 等同于 func(1, 2, 3)

kwargs = {"a": 1, "b": 2}
func(**kwargs)       # 等同于 func(a=1, b=2)

with 语句与上下文管理器

# 文件操作(自动关闭)
with open("file.txt", "r", encoding="utf-8") as f:
    content = f.read()
# 退出 with 块后文件自动关闭,即使发生异常

# 多个上下文管理器
with open("input.txt") as fin, open("output.txt", "w") as fout:
    fout.write(fin.read())

# 自定义上下文管理器
from contextlib import contextmanager

@contextmanager
def timer():
    import time
    start = time.time()
    yield
    print(f"Elapsed: {time.time() - start:.3f}s")

with timer():
    expensive_operation()

推导式全家桶

data = range(10)

# list comprehension
squares = [x**2 for x in data]

# dict comprehension
square_map = {x: x**2 for x in data}

# set comprehension
unique_mods = {x % 3 for x in data}

# generator expression(惰性求值,省内存)
gen = (x**2 for x in data)
total = sum(x**2 for x in data)    # 直接传生成器表达式

# 嵌套推导式
matrix = [[1,2,3],[4,5,6],[7,8,9]]
flat = [x for row in matrix for x in row]

常用标准库速览

# pathlib:现代文件路径操作(替代 os.path)
from pathlib import Path
p = Path("/home/user/docs")
p / "file.txt"           # 路径拼接
p.exists()               # 是否存在
p.glob("*.py")           # 通配符
p.read_text()            # 读取文件
p.write_text("hello")    # 写入文件

# json
import json
text = json.dumps({"key": "value"}, ensure_ascii=False, indent=2)
data = json.loads(text)

# re(正则)
import re
m = re.search(r"\d+", "abc123def")
m.group()   # 123
re.findall(r"\w+", "hello world")   # ['hello', 'world']

# datetime
from datetime import datetime, timedelta
now = datetime.now()
tomorrow = now + timedelta(days=1)
now.strftime("%Y-%m-%d %H:%M:%S")
datetime.strptime("2026-01-01", "%Y-%m-%d")

# collections
from collections import Counter, defaultdict, deque
Counter("abracadabra")    # {'a': 5, 'b': 2, ...}
dd = defaultdict(list)
dd["key"].append(1)       # 自动初始化

快速对比:Python vs 其他语言

特性 Python Java/C++ JavaScript
变量声明 x = 1 int x = 1; let x = 1
字符串插值 f"{x}" String.format() `${x}`
列表/数组 list ArrayList Array
字典/Map dict HashMap Object/Map
空值 None null null/undefined
注释 # ... // ... // ...

Python 的哲学:显式优于隐式,可读性最重要(The Zen of Python)。