[course]05 —— 二维列表
1. Creating 2d Lists
Static Allocation
# create a 2d list with fixed values (static allocation)
a = [ [ 2, 3, 4 ] , [ 5, 6, 7 ] ]
print(a)Dynamic (Variable-Length) Allocation
Wrong: Cannot use * (Shallow Copy)
# Try, and FAIL, to create a variable-sized 2d list
rows = 3
cols = 2
a = [ [0] * cols ] * rows # Error: creates shallow copy
# Creates one unique row, the rest are aliases!
print("This SEEMS ok. At first:")
print(" a =", a)
a[0][0] = 42
print("But see what happens after a[0][0]=42")
print(" a =", a)Right: Append Each Row
Another good option: use a list comprehension
Best option: make2dList()
2. Getting 2d List Dimensions
3. Copying and Aliasing 2d Lists
Wrong: Cannot use copy.copy (shallow copy)
Right: use copy.deepcopy
Limitations of copy.deepcopy
Advanced: alias-breaking deepcopy
4. Printing 2d Lists
5. Nested Looping over 2d Lists
6. Accessing 2d Lists by Row or Column
Accessing a whole row
Accessing a whole column
Accessing a whole column with a list comprehension
7. Non-Rectangular ("Ragged") 2d Lists
8. 3d Lists
Last updated
Was this helpful?