跳转至

2 使用数据结构构造抽象

2.1 序列

digits  = [1, 8, 2, 8]

len(digits) = 4

digits[3] = 8         # getitem(digits, 3)

[2, 7] + digits * 2   # add([2, 7], mul(digits, 2))
[2, 7, 1, 8, 2, 8, 1, 8, 2, 8]

pairs = [[10, 20], [30, 40]]
pairs[1] = [30, 40]
pairs[1][0] = 30

2.2 For循环

for <name> in <expression>:
    <suite>

2.3 Sequence Unpacking in For Statements(序列解包)

pairs = [[1, 2], [2, 2], [3, 2], [4, 4]]
same_count = 0

for x, y in pairs:
    if x == y:
        same_count += 1

2.4 Equal and Same

b = [10]
a = b
>>> a == b
True
>>> b.append(20)
>>> a == b
True
b = [10]
a = [10]
a == b
>>> b.append(20)
>>> a == b
False
>>> s = [3, 4]
>>> t = [5, 6]
>>> s.append(t)
>>> s
[3, 4, [5, 6]]
>>> t = 0
>>> s
[3, 4, [5, 6]]
>>> t
0
>>> t = [5, 6]
>>> s.extend(t)
>>> s
[3, 4, [5, 6], 5, 6]
>>> t = 0
>>> s
[3, 4, [5, 6], 5, 6]

评论