Code Cheat Sheet
The files in Source all live in 编程/教材/.
输入关键词开始查 —— 多个词用空格隔开(都要命中)。
1 Data in
| What I want to do | Search keywords | Code | One-line explanation | Source | Pitfall |
|---|---|---|---|---|---|
| Read a text file | read read-file open-file | with open("a.txt", encoding="utf-8") as f:text = f.read() |
Read it all into a string at once | Python Core §6 | Always use with, otherwise the file never closes |
| Read line by line (big files) | read-line big-file | with open("a.txt", encoding="utf-8") as f:for line in f:print(line.rstrip()) |
One line at a time, no memory blowup | Stage 10 | The line already ends with \n; strip it with rstrip() |
| Read into a list of lines | readlines | lines = f.readlines() |
Read everything into a list | Stage 10 | Big files will blow up memory |
| Read a CSV into a table | read-csv read-table | df = pd.read_csv("trials.csv") |
One line, header detected automatically | Research Computing §3 | For non-ASCII paths/encoding use encoding="utf-8" |
| Read Parquet (fast) | parquet big-data | df = pd.read_parquet("a.parquet") |
Format built for big data | Research Computing §5 | Requires pyarrow installed first |
| Split a CSV line into fields | split comma | parts = [p.strip() for p in line.split(",")] |
Split on commas into a list | Stage 9 | strip() first, " 18 " is not "18" |
| Convert a string to a number | convert-number type-cast | float(s.strip()) / int(s) |
String → number | Stage 9 | Whitespace raises ValueError; strip first |
| Skip blank lines and comments | skip-blank-line | if not line or line.startswith("#"):continue |
The usual dirty-data handling | Stage 10 | — |
| Locate a path when reading files | path where-is-file | from pathlib import PathHERE = Path(__file__).resolve().parentp = HERE / "data" / "raw.csv" |
Find files relative to the script itself | Stage 10 | ⚠️ Never hard-code /Users/... |
2 Looking at data
| What I want to do | Search keywords | Code | One-line explanation | Source | Pitfall |
|---|---|---|---|---|---|
| Preview the first few rows | preview head | df.head() |
See what the data looks like | Scientific Computing Stack §3 | The first thing to do with any dataset |
| See the shape (rows × columns) | shape | df.shape / arr.shape |
Returns (rows, columns) |
Scientific Computing Stack §2 | The first thing when debugging numpy |
| See each column's type | type dtype | df.dtypes / arr.dtype |
Check whether anything got read as a string | Scientific Computing Stack §3 | A numeric column read as object is the classic gotcha |
| See a statistical summary of a column | describe summary | df.describe() |
Gives count/mean/std/min/max in one go | Scientific Computing Stack §3 | — |
| Count the rows | row-count how-many | len(df) / len(records) |
How much data | Stage 9 | — |
| See a string's "true face" | repr whitespace newline | print(repr(s)) |
Reveals spaces and newline characters | Stage 9 | A plain print hides whitespace |
| See an array's number of dimensions | dimension ndim | arr.ndim |
1 = vector, 2 = matrix | Scientific Computing Stack §2 | — |
| See the total number of elements | size | arr.size |
Count of all elements | Scientific Computing Stack §2 | Not the same thing as shape |
3 Selecting data
| What I want to do | Search keywords | Code | One-line explanation | Source | Pitfall |
|---|---|---|---|---|---|
| Take one column by name | get-column select-column | df["rt"] |
Select by name, no need to remember the position | Scientific Computing Stack §3 | A missing column name raises KeyError |
| Filter rows by a condition | filter condition | df[df["correct"] == 1] |
Keep only the rows that satisfy the condition | Research Computing §3 | — |
| Filter on several conditions | multiple-conditions and | df[(df["rt"] > 200) & (df["rt"] < 2000)] |
Both conditions must hold | Research Computing §3 | ⚠️ Use &, not and, and parenthesise every condition |
| Boolean filtering on an array | boolean-indexing | a[a > 3] |
Keep only the elements greater than 3 | Scientific Computing Stack §2 | The condition must be wrapped in parentheses |
| Replace values conditionally | where if-true | np.where(a > 3, a, 0) |
Keep if it satisfies, otherwise set to 0 | Scientific Computing Stack §2 | Three arguments: condition, value if true, value if false |
| Drop outlier reaction times | drop outlier clean | clean = rts[(rts >= 0.2) & (rts <= 3.0)] |
Keep only the plausible range | Stage 10 | Fix the threshold before analysis and write it into the paper |
| Drop incorrect trials | drop-wrong keep-correct | df = df[df["correct"] == 1] |
Analyse only correct trials | Research Computing §3 | Some analyses need the error trials — think it through |
| Take a slice of a list/string | slice | s[0:4] / lst[1:] |
Start inclusive, end exclusive | Python Core §4 | s[0:4] gives 4 characters (0,1,2,3) |
| Reverse it | reverse | s[::-1] |
Step of -1 | Python Core §4 | — |
| Get an element by position | index which-one | lst[0] / lst[-1] |
First / last | Python Core §4 | Out of range raises IndexError (slices do not) |
| Get a value from a dict by key | dict get key | d.get("key", default) |
No error even when the key is missing | Python Core §1 | d["key"] raises KeyError, .get() does not |
| Deduplicate | dedupe unique | set(nums) / list(set(nums)) |
Deduplicate in one line | Stage 8 | Order is lost |
| Group | group groupby | df.groupby("condition")["rt"].mean() |
Mean per group | Scientific Computing Stack §3 | The result needs .reset_index() to save as a normal CSV |
4 Computing
| What I want to do | Search keywords | Code | One-line explanation | Source | Pitfall |
|---|---|---|---|---|---|
| Operate on a whole array at once | vectorise no-for | arr + 10 / arr * 2 / arr ** 2 |
Computed in one shot, hundreds of times faster | Scientific Computing Stack §1 | If you have a for loop, there is usually room to optimise |
| Sum | sum | arr.sum() / sum(lst) |
Add everything up | Scientific Computing Stack §2 | — |
| Sum along columns / rows | axis rows columns | arr.sum(axis=0) per columnarr.sum(axis=1) per row |
Collapse along one direction | Scientific Computing Stack §2 | ⚠️ axis=0 eliminates the rows — get it backwards and every result is wrong |
| Mean | mean average | arr.mean() / df["rt"].mean() |
Arithmetic mean | Scientific Computing Stack §2 | Check for an empty list first, or you divide by 0 |
| Median | median | df["rt"].median() |
The middle value | Stage 12 | With an even count it averages the middle two |
| Standard deviation | std standard-deviation | df["rt"].std() / np.std(a) |
Spread | Stage 12 | np.std divides by n by default, pd.Series.std by n-1 (sample SD) |
| Max / min | max min | arr.max() / min(lst) |
Extremes | Scientific Computing Stack §2 | — |
| Compute several statistics at once | agg summarise | df.groupby("condition")["rt"].agg(["mean","median","std","count"]) |
Several numbers from one table | Scientific Computing Stack §3 | — |
| Correlate two columns | correlation pearson | stats.pearsonr(x, y) |
Returns r and p |
Scientific Computing Stack §5 | Do not try it on identical data — you get a precision warning |
| Compare two group means | t-test ttest | stats.ttest_ind(g1, g2) |
Independent-samples t test | Scientific Computing Stack §5 | For the same people before/after, use ttest_rel |
| Compare the same people before/after | paired-ttest | stats.ttest_rel(before, after) |
Paired-samples t test | Scientific Computing Stack §5 | — |
| Normal-distribution probability | normal cdf pdf | stats.norm.pdf(0) densitystats.norm.cdf(0) cumulative |
Probability density / cumulative probability | Scientific Computing Stack §5 | — |
| Solve a system of linear equations | solve system-of-equations | np.linalg.solve(A, b) |
Solves Ax = b | Stage 9 | Faster and more stable than inverting then multiplying |
| Invert a matrix | inverse inv | np.linalg.inv(A) |
The matrix's "division" | Stage 9 | Raises LinAlgError when det=0 |
| Determinant | determinant det | np.linalg.det(A) |
A single number | Stage 8 | Close to 0 means nearly singular |
| Pseudoinverse (fallback when collinear) | pseudoinverse pinv | np.linalg.pinv(A) |
Gives a solution even when not invertible | Stage 16 | Under the hood it is the SVD |
| Eigenvalues (general matrix) | eigenvalue eig | vals, vecs = np.linalg.eig(A) |
Eigenvalues + eigenvectors | Stage 13 | May return complex numbers |
| Eigenvalues (symmetric matrix) | eigenvalue eigh | vals, Q = np.linalg.eigh(A) |
Faster, more stable, sorted ascending | Stage 15 | ⚠️ Feeding it a non-symmetric matrix silently gives wrong results |
| Singular value decomposition | svd | U, S, Vt = np.linalg.svd(A) |
Works for any matrix | Stage 16 | U and Vt have different sizes; reconstruction needs truncation |
| Matrix power | matrix-power power | np.linalg.matrix_power(A, k) |
A to the power k | Stage 15 | Do not use A ** k (that is element-wise) |
| Rank | rank | np.linalg.matrix_rank(A) |
Number of independent directions | Stage 10 | Collinearity is judged by the condition number, not the rank |
| Condition number | condition-number cond | np.linalg.cond(A) |
How ill-conditioned it is | Stage 10 | > 30 be suspicious, > 1000 basically untrustworthy |
| Numerical integration | integral quad | scipy.integrate.quad(f, a, b) |
Evaluate a definite integral | Stage 12 | Returns (value, error) |
| Symbolic differentiation/integration | sympy diff integrate | sp.diff(x**2, x)sp.integrate(x**2, x) |
Exact answers (with a formula) | Stage 11 | With sympify on a string, the symbols must match |
| Compress a loop into one line | comprehension | [i**2 for i in range(5)] |
List comprehension | Python Core §4 | Past two levels, go back to a for loop |
| Comprehension with a condition | comprehension condition | [i for i in range(5) if i > 2] (sieve)[i if i > 2 else 0 for i in range(5)] (transform) |
Sieve and transform | Python Core §4 | ⚠️ The two if positions are completely different |
| Memory-saving "comprehension" | generator save-memory | (i**2 for i in range(10**7)) |
Compute as you go | Python Core §4 | Empty once used — you cannot iterate it twice |
| Swap two variables | swap | a, b = b, a |
No temp variable needed | Stage 9 | — |
| Compare floats safely | float isclose | math.isclose(a, b) |
Avoids precision problems | Python Core §7 | ⚠️ Never compare floats with == |
| Reproducible random numbers | random seed | rng = np.random.default_rng(42) |
Makes results reproducible | Research Computing §4 | With plain random you also need random.seed(42) |
5 Plotting
| What I want to do | Search keywords | Code | One-line explanation | Source | Pitfall |
|---|---|---|---|---|---|
| Draw a line plot | line-plot curve plot | plt.plot(x, y, label="line") |
Trend over time | Scientific Computing Stack §4 | — |
| Draw a bar chart | bar-chart bar | plt.bar(x, y, yerr=err) |
Compare conditions (standard in papers) | Scientific Computing Stack §4 | yerr adds error bars |
| Draw a scatter plot | scatter | plt.scatter(x, y) |
See correlations, individual differences | Scientific Computing Stack §4 | — |
| Draw a histogram | histogram hist | plt.hist(data, bins=30) |
See a distribution (e.g. RT distribution) | Scientific Computing Stack §4 | bins sets the number of bars |
| Add a title and axis labels | title label | plt.xlabel("x")plt.ylabel("y")plt.title("title") |
Say clearly what is plotted | Scientific Computing Stack §4 | Every figure needs axis labels, or nobody can read it |
| Show the legend | legend | plt.legend() |
Shows what label says |
Scientific Computing Stack §4 | Call it after the label in plot |
| Save as an image | save export savefig | plt.savefig("plot.png", dpi=150, bbox_inches="tight") |
Write the file | Scientific Computing Stack §4 | ⚠️ Must come before plt.show() |
| Make CJK text render on the plot | cjk font boxes | plt.rcParams["font.sans-serif"] = ["Arial Unicode MS", "PingFang SC"]plt.rcParams["axes.unicode_minus"] = False |
CJK text and minus signs display properly | Scientific Computing Stack §4 | The second line is the one people forget — otherwise the minus sign becomes a box |
| Generate coordinates for plotting | linspace evenly-spaced | x = np.linspace(-5, 5, 200) |
Includes the endpoint, use this for plotting | Scientific Computing Stack §2 | arange excludes the endpoint, so you can lose the last segment |
6 Saving
| What I want to do | Search keywords | Code | One-line explanation | Source | Pitfall |
|---|---|---|---|---|---|
| Write a text file | write-file save | with open("out.txt", "w", encoding="utf-8") as f:f.write("text\n") |
Write to a file | Stage 10 | ⚠️ write() does not add a newline, write \n yourself |
| Append instead of overwrite | append | with open("log.txt", "a", encoding="utf-8") as f: |
Add at the end | Stage 10 | ⚠️ "w" wipes the original file immediately, no undo |
| Save a table as CSV | save-csv export | df.to_csv("out.csv", index=False) |
Save as a table | Scientific Computing Stack §3 | index=False, or you save an extra row-number column |
| Save as Parquet | save-parquet | df.to_parquet("out.parquet") |
Big-data format | Research Computing §5 | Needs pyarrow |
| Create a directory (only if missing) | create-directory mkdir | p.parent.mkdir(parents=True, exist_ok=True) |
Avoids the "directory already exists" error | Stage 10 | Both arguments are almost always needed |
| Check whether a file exists | file-exists exists | Path("a.txt").exists() |
Check existence | Stage 10 | — |
7 Code organisation
| What I want to do | Search keywords | Code | One-line explanation | Source | Pitfall |
|---|---|---|---|---|---|
| Define a function | function def | def mean_of(nums):return sum(nums) / len(nums) |
Wrap up a piece of logic | Stage 4 | Decide clearly what it returns |
| Define a function with a default value | default-argument | def f(x, threshold=0.8): |
Can be omitted at the call site | Stage 5 | ⚠️ Never use a mutable object as a default (see below) |
| Want a parameter that "defaults to an empty list" | mutable-default-argument | def add(x, lst=None):if lst is None:lst = [] |
Use None as a placeholder |
Python Core §1 | ⚠️⚠️ def add(x, lst=[]) is the classic trap |
| Return several values at once | return-multiple tuple | def f(): return min(nums), max(nums)lo, hi = f() |
What comes back is a tuple | Stage 9 | — |
| Define a class | class | class Subject:def __init__(self, sid):self.sid = sid |
Bundle data and behaviour together | Stage 12 | self means "this instance itself" |
| Reuse the parent class in a subclass | inheritance super | class Child(Parent):def __init__(self, x, y):super().__init__(x) |
Do the parent's work first | Stage 13 | ⚠️ Skip super().__init__ and attributes go missing |
| Make an object print nicely | repr | def __repr__(self):return f"Subject({self.sid!r})" |
For debugging output | Stage 12 | Without it you get <object at 0x...> |
Make an object support len() |
len dunder | def __len__(self):return len(self.rts) |
Support built-in syntax | Stage 12 | — |
| Read a method like an attribute | property read-only | @propertydef mean_rt(self):return sum(self._rts)/len(self._rts) |
s.mean_rt without parentheses |
Stage 13 | By default cannot be assigned to |
| Copy a list | copy | b = a.copy() / b = a[:] |
A real, separate copy | Python Core §1 | b = a is not a copy, it just sticks on another label |
| Deep copy (nested structures) | deep-copy deepcopy | import copyb = copy.deepcopy(a) |
Copies the inside too | Python Core §1 | A shallow copy "bleeds" when nested |
| Test whether it is the same object | is identity | a is b |
Same object? | Python Core §2 | Only use is when testing for None |
Test whether it is None |
none test | if x is None: |
The standard way | Python Core §2 | Do not write == None |
| Split code across several files | module import | # utils.py defines the functionimport utils in # main.pyutils.my_func() |
One file, one job | Stage 11 | Module name = file name minus .py |
| Make a file both runnable and importable | main | if __name__ == "__main__":main() |
Runs only when executed directly | Stage 11 | Every runnable file should have this block |
| Set up an environment | virtual-environment venv | python -m venv .venvsource .venv/bin/activate |
A separate package directory | Stage 16 | ⚠️ Do not commit .venv/ to Git |
| Record the dependency list | requirements | pip freeze > requirements.txtpip install -r requirements.txt |
So others can reproduce it | Stage 16 | — |
Manage resources with with |
with context | with open("a.txt") as f: |
Cleaned up automatically on exit | Python Core §6 | Use it for every file you open |
| Add behaviour to a function without changing it | decorator | @functools.wraps(func)def wrapper(*args, **kwargs): |
Wrap it in a layer | Python Core §6 | Do not skip functools.wraps |
8 Debugging
| What I want to do | Search keywords | Code | One-line explanation | Source | Pitfall |
|---|---|---|---|---|---|
| How to read an error | error traceback | Look at the last line first (type + reason) then the second/third from last (file + line number) |
The order to read tracebacks in | Engineering Skills §3 | The last line is the error itself |
| Set a breakpoint in the code | breakpoint debugger | breakpoint() |
The program pauses here | Engineering Skills §3 | ⚠️ Remember to delete it before committing |
| How to drive the debugger | pdb commands | p show variable / n next line / c continue / q quit |
Interactive debugging | Engineering Skills §3 | The ones you use most are p, n, c |
| Print a variable's name and value | f-string debug | print(f"{total=}") |
Variable name included automatically | Stage 14 | Far clearer than print(total) |
| Raise an error on purpose (stop when the data is wrong) | raise exception | raise ValueError(f"rt must be positive, got {rt}") |
Fail fast | Stage 12 | Better than letting it run on with bad data |
| Keep the original error cause | raise-from | raise ValueError("...") from e |
The error chain stays intact | Stage 14 | — |
| Handle a possible error | try-except | try:rt = float(s)except ValueError:rt = 0.0 |
A fallback when it fails | Stage 10 | ⚠️ Do not write except Exception: pass (silently swallows errors) |
| The file may not exist | FileNotFound handling | try:with open(p) as f: ...except FileNotFoundError:... |
Give a default when the file is missing | Stage 10 | When the file must exist, do not catch it — let it crash |
| Write a test | test assert pytest | assert mean_of([1,2,3]) == 2 |
Check the case | Stage 14 | For small projects assert is enough |
| Run tests with pytest | pytest | pytest -v |
Runs every test_*.py |
Engineering Skills §4 | The file name must start with test_ to be discovered |
| Check whether two shapes can be combined | broadcast broadcast-failure | Right-align and compare element by element: equal, or one of them is 1 | The numpy broadcasting rule | Scientific Computing Stack §2 | ⚠️ print(a.shape) first |
| Stand a 1-D array up | reshape add-dimension | c = np.array([100,200]).reshape(2, 1) |
So it can broadcast along rows | Scientific Computing Stack §2 | — |
| See what is installed in the environment | version installed-packages | import importlib.metadata as md; md.version("numpy") |
Check a package version | Stage 16 | Debugging "it works on my machine" |
| See which Python this is | interpreter path | import sys; print(sys.executable) |
The interpreter currently in use | Stage 16 | It changes after you activate a virtual environment |
9 Git
| What I want to do | Search keywords | Code | One-line explanation | Source | Pitfall |
|---|---|---|---|---|---|
| Turn a directory into a repository | init | git init |
Once per project | Engineering Skills §1 | — |
| See what the current state is | status | git status |
The most-typed command, read-only | Engineering Skills §1 | Run it first for any Git problem |
| See what changed | diff | git diff |
Shows changes line by line | Stage 13 | git diff --staged shows the staging area |
| Put changes into the staging area | stage add | git add filename |
Pick what to commit | Engineering Skills §1 | git status first, then add |
| Commit a version | commit | git commit -m "fix blank-line crash" |
Save a version in history | Engineering Skills §1 | The message should start with a verb + say what you did |
| See the history | log history | git log --oneline |
One line each | Stage 13 | --graph shows the branch graph |
| Create a branch and switch to it | branch | git switch -c new-feature / git checkout -b new-feature |
Change code in a parallel universe | Stage 15 | A branch is just a pointer, virtually free |
| Switch back to main | switch | git switch main |
Files become main's version | Stage 15 | — |
| Merge a branch | merge | git merge new-feature |
Bring the branch's changes in | Stage 15 | Conflicts are possible (see below) |
| Resolve a conflict | conflict | Edit the file by hand, delete the three marker lines <<<<<<<, =======, >>>>>>>, then git add + git commit |
All three markers must go | Stage 15 | ⚠️ Leaving the markers = syntax error |
| Connect to GitHub | remote push | git remote add origin <url>git push -u origin main |
Push to the remote | Stage 15 | -u is only needed the first time |
| Pull other people's updates | pull fetch | git pull (= fetch + merge)git fetch (download only, leaves the working tree alone) |
Sync with the remote | Stage 15 | When unsure, fetch first and look |
| Undo changes in the working tree | undo restore | git restore file |
⚠️ The changes are lost forever | Stage 15 | Run git diff first to see exactly what |
| Take something out of the staging area | unstage | git restore --staged file |
The file's contents stay the same | Stage 15 | A safe operation |
| Put changes aside for now | stash | git stash / git stash pop |
The safest "park it for a moment" | Stage 15 | Use this when you are unsure |
| Ignore certain files | gitignore ignore | see the .gitignore section |
Do not commit caches/secrets/big data | Engineering Skills §1 | ⚠️ A comment must be on its own line; a trailing comment disables the rule |
| Stop tracking a file | rm cached | git rm --cached file |
Removes it from Git but keeps it locally | Stage 13 | .gitignore does nothing for already-tracked files — use this |
The standard .gitignore:
# a comment must be on its own line (a trailing comment breaks the rule!)
# Python cache
__pycache__/
*.pyc
# secrets (⚠️ never commit these)
.env
# analysis outputs (can be regenerated from the raw data)
data/processed/
results/
# system files
.DS_Store
⚠️ If you commit a secret you must rotate it — even if you delete the file later, it is still in the Git history, and anyone who clones can dig it out.
10 Environment
| What I want to do | Search keywords | Code | One-line explanation | Source | Pitfall |
|---|---|---|---|---|---|
| Create a virtual environment | venv virtual-environment | python -m venv .venv |
A separate package directory | Stage 16 | One per project |
| Activate / deactivate | activate | source .venv/bin/activatedeactivate |
Make python point at it |
Stage 16 | After activating, which python changes |
| Install a package | install pip-install | pip install numpy pandas |
Installs a package (only affects this environment) | Stage 16 | — |
| Install from a list | requirements | pip install -r requirements.txt |
Reproduce the environment in one command | Stage 16 | — |
| See which packages are installed | list pip-list | pip list / pip freeze |
Lists installed packages and versions | Stage 16 | freeze output can be used directly as a requirements list |
| Create an environment with conda | conda-create | conda create -n myenv python=3.12conda activate myenv |
More than venv: manages non-Python dependencies too | Stage 16 | Less hassle when installing PyTorch |
| Export / rebuild a conda environment | environment.yml | conda env export > environment.ymlconda env create -f environment.yml |
A full environment snapshot | Stage 16 | — |
| Check a package's version | version | import importlib.metadata as mdmd.version("numpy") |
For debugging | Stage 16 | — |
Common commands on this machine (your Python lives in miniconda):
# run a script
~/miniconda3/bin/python script.py
# install a package
~/miniconda3/bin/python -m pip install package-name
# check the version
~/miniconda3/bin/python -c "import sys; print(sys.version)"
11 How to practise this table
Do not memorise it. This table is for looking things up. The way you actually master it is:
| Step | What to do |
|---|---|
| 1 | When you hit a problem, search this table first (Cmd+F on the keyword column) |
| 2 | Once you find it, copy it over and try changing a variable name |
| 3 | Use it enough and you remember — this is retrieval practice (covered in Stage 14) |
| 4 | For anything not in the table, search the official Python docs or the pandas docs |
⭐ Remembering that this table exists matters far more than remembering every row in it.
Knowing "there is such a thing you can use" already solves half the problem.
12 Self-check
Every code snippet in this table has actually been run and verified in the four sets of notes. To reproduce it yourself:
cd ~/Desktop/大一/编程/教材
~/miniconda3/bin/python 自检脚本.py
It verifies the individual claims in the notes (shared aliases, mutable default arguments, broadcasting, vectorised speed-up, random seeds, and so on).
There is also a site-wide self-check you can run:
~/miniconda3/bin/python ~/Desktop/大一/验证.py