If I have the following matrix, which the input format is a list of lists:
B | T | E |
---|---|---|
0 | 1 | 0 |
0 | 1 | 1 |
0 | 2 | 1 |
1 | 2 | 0 |
How can I construct the following python matrix:
JavaScript
x
4
1
0 1
2
D = [[{1}, {1,2}], 0
3
[{2}, {}]] 1
4
Where the elements of D, merge the pairs (B,E) with it’s respective T. Example: (0,1) in the above matrix, have T = 1 and T = 2, so in D matrix it should be a set {1,2}. Since there is no (1,1) pair, it should be a empty set {}.
How could a do that in a “pythonic” way?
Advertisement
Answer
You can use collections.defaultdict
:
JavaScript
1
10
10
1
from collections import defaultdict
2
m = [[0, 1, 0], [0, 1, 1], [0, 2, 1], [1, 2, 0]]
3
d = defaultdict(dict)
4
for b, t, e in m:
5
d[b][e] = [t] if e not in d[b] else [*d[b][e], t]
6
7
l = {i for b in d.values() for i in b}
8
result = [[set(k.get(j, [])) for j in l] for k in d.values()]
9
print(result)
10
Output:
JavaScript
1
3
1
[[{1}, {1, 2}],
2
[{2}, set()]]
3