Skip to content
Advertisement

Pythonic way to “condense” a matrix

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

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

Output:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement