Skip to content

Commit a2f843c

Browse files
committed
post: python tricks 02
1 parent c30b138 commit a2f843c

File tree

1 file changed

+111
-1
lines changed

1 file changed

+111
-1
lines changed

content/posts/2025-12-16_python-distilled-02.md

Lines changed: 111 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,114 @@ tags = ['Python']
3939

4040
## Operations Involving Iterables
4141

42-
TODO: 消耗性迭代器
42+
任何可迭代对象都可以展开,如 list, tuple and set,都通过星号(\*)。
43+
44+
```Python
45+
items = [1, 2, 3]
46+
a = [10, *items, 1] # [10, 1, 2, 3, 1]
47+
b = (*items, 10, *items) # [1, 2, 3, 10, 1, 2, 3]
48+
c = {10, 11, *items} # {10, 11, 1, 2, 3}
49+
```
50+
51+
在上面例子中,item 简单的被粘贴到 list, tuple, set 中,就和手动输入进去一样。
52+
有时候这种展开 expansion 被称为“展开操作符” splatting。
53+
54+
在定义字面量的时候,可以展开任意多的可迭代对象。
55+
但要注意的是,许多可迭代对象只能迭代一次。
56+
如果你使用星号 \* 将其展开,其内容会被消耗掉,且该可迭代对象在后续迭代中将不再产生任何值。
57+
58+
## Operations on Sequences
59+
60+
序列 sequence 是有大小的可迭代对象,并且允许通过从 0 开始的索引访问。
61+
例如 strings, lists and tuples.
62+
63+
加号运算符 `+` 将两个同类型的 sequence 拼接起来。
64+
乘法运算符 `*` 将序列复制 n 份,但这里实际上是浅拷贝的引用,而不是复制内存元素的值。
65+
66+
如果不希望使用引用,可以使用 `list()`
67+
68+
```Python
69+
a = [3, 4, 5]
70+
c = [list(a) for _ in range(4)] # list() makes a copy of a list
71+
```
72+
73+
## Operations on Mutable Sequences
74+
75+
切片赋值是将 `[i:j]``i ≤ k < j` 的元素替换为新列表,而不是一一对应才能替换,例如:
76+
77+
```Python
78+
a = [1, 2, 3, 4, 5]
79+
a[1] = 6 # [1, 6, 3, 4, 5]
80+
a[2:4] = [10, 11] # [1, 6, 10, 11, 5]
81+
a[3:4] = [-1, -2, -3] # [1, 6, 10, -1, -2, -3, 5]
82+
a[2:] = [0] # [1, 6, 0]
83+
```
84+
85+
切片还可能有步幅 stride 参数,这时候才需要在切片赋值列表时一一对应
86+
87+
```Python
88+
a = [1, 2, 3, 4, 5]
89+
a[1::2] = [10, 11] # [1, 10, 3, 11, 5]
90+
a[1::2] = [30, 40, 50] # ValueError
91+
```
92+
93+
## Operations on Mappings
94+
95+
映射 mappings 是一种相关联的键值对关系,内置的 dict 类型就是一个例子。
96+
当使用元组 tupel 作为键是,可以省略圆括号,并使用逗号分开值
97+
98+
```Python
99+
d = { }
100+
d[1, 2, 3] = "foo"
101+
d[1, 0, 3] = "bar"
102+
```
103+
104+
上面代码等同于
105+
106+
```Python
107+
d[(1, 2, 3)] = "foo"
108+
d[(1, 0, 3)] = "bar"
109+
```
110+
111+
使用元组作为键是映射中创建符合键的常用技巧。
112+
113+
## Generator Expressions
114+
115+
生成器表达式是一种对象,有着和列表推导式一样的计算方法,但迭代产生值。
116+
语法和列表推导式相同,编写时使用圆括号 parentheses 而不是方括号 square brackets。
117+
118+
生成器只能迭代一次,如果尝试迭代第二次,什么都不会得到。
119+
但是生成器可以被转换为列表
120+
121+
```Python
122+
clist = list(comments)
123+
```
124+
125+
当我们将生成器表达式作为单个函数参数传递的时候,可以去掉外层的括号
126+
127+
```Python
128+
sum((x*x for x in values))
129+
sum(x*x for x in values) # Extra parens removed
130+
```
131+
132+
## The Attribute (.) Operator
133+
134+
操作符点 `.` 用于访问一个对象的属性
135+
136+
```Python
137+
foo.x = 3
138+
print(foo.y)
139+
a = foo.bar(3, 4, 5)
140+
```
141+
142+
一个表达式中可以使用多个点操作符,但从风格上来讲,一般不会创建很长的这种写法。
143+
144+
```Python
145+
foo.bar(3, 4, 5).spam
146+
```
147+
148+
## The Function Call() Operator
149+
150+
`f(args)` 这样写是对函数 `f` 进行调用,函数的每个参数都是一个表达式。
151+
在调用函数前,所有表达式都会从左到右调用求值。
152+
这有时被称为应用序求值 application order evaluation。

0 commit comments

Comments
 (0)