-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathset-expr.py
More file actions
80 lines (55 loc) · 1.1 KB
/
set-expr.py
File metadata and controls
80 lines (55 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# set 生成式
## simple
a = {0, 1, 2, 3}
b = {i + 1 for i in a}
assert 1 in b
assert 2 in b
assert 3 in b
assert 4 in b
## if in front, as a map
a = {0, 1, 2, 3}
b = {i if i % 2 == 1 else 0 for i in a}
assert len(b) == 3
assert 0 in b
assert 1 in b
assert 3 in b
## if in back, as a filter
a = {0, 1, 2, 3}
b = {i for i in a if i % 2 == 1}
assert len(b) == 2
assert 1 in b
assert 3 in b
## multi list
a = {0, 1}
b = {10, 11}
c = {n - m for m in a for n in b}
### 先循环 a 后循环 b
assert len(c) == 3
assert 9 in c
assert 10 in c
assert 11 in c
## nested list expr
### set is not hashable
### ref: https://stackoverflow.com/questions/6754102/typeerror-unhashable-type
a = [
{0, 1},
{2, 3}
]
b = {j for i in a for j in i}
assert len(b) == 4
assert 0 in b
assert 1 in b
assert 2 in b
assert 3 in b
## random if and for
a = [
{0, 1, 2},
{0, 1},
{0,}
]
b = {j for i in a if len(i) == 2 for j in i if j == 0}
assert len(b) == 1
assert 0 in b
c = {j if j == 1 else 10 for i in a if len(i) == 2 for j in i if j == 0}
assert len(c) == 1
assert 10 in c