# Transforming a list of list

I have two lists :

l1=[([๐ฐ,๐ฑ],๐ฐ),([๐ฐ,๐ฒ],๐ฒ),([๐ฑ,๐ฒ],๐ฑ)]
l2=[[33,27],[25,35],[42,18]]


This two list must be read like this ([A, B], A) : A win in the duel with B and the score are 33 for A and 27 for B. I would like to transfer this information in a table or a matrix such that in line one has the score of each duelist against the others that is :

A = [[0,33,25],[27,0, 42],[35,18,0]]

of course this is an example. The solution must be generic. In the time I have tried to find an elegant solution, I have encountered the following problem : how to remove Rien from all the sublist in :

l3=[[33,๐๐๐๐,25,๐๐๐๐,๐๐๐๐,๐๐๐๐],[๐๐๐๐,27,๐๐๐๐,๐๐๐๐,42,๐๐๐๐],[๐๐๐๐,๐๐๐๐,๐๐๐๐,35,๐๐๐๐,18]]

and insert the 0according to the A matrix. Thanks for your help.

edit retag close merge delete

Please provide self-contained code that can be copied and pasted.

Currently, we get name errors, as neither A, B, C, Rien are defined.

Calling A the table or matrix when one of the duelists is also A seems error-prone.

( 2021-01-20 19:17:13 +0200 )edit

Sort by ยป oldest newest most voted

The function individual_duel_scores below returns a dictionary of dictionaries with the duel scores.

One can use it to build a matrix for all the duel scores.

The function:

def individual_duel_scores(duel_winners, duel_scores):
r"""
Return a dictionary of dictionaries giving the scores
of each players against each other player.
"""
from collections import defaultdict
players = sorted(set(flatten(duel_winners)))
scores = defaultdict(lambda: defaultdict(int))
for ((a, b), _), (x, y) in zip(duel_winners, duel_scores):
scores[a][b] = x
scores[b][a] = y
return scores


Define the players:

sage: A, B, C = 'ABC'


The duel winners and the scores (called l1 and l2 in the question):

sage: duel_winners = [([๐ฐ, ๐ฑ], ๐ฐ), ([๐ฐ, ๐ฒ], ๐ฒ), ([๐ฑ, ๐ฒ], ๐ฑ)]
sage: duel_scores = [[33, 27], [25, 35], [42, 18]]


Individual scores:

sage: scores = individual_duel_scores(duel_winners, duel_scores)


Extract the players from the scores:

sage: players = sorted(scores)
sage: players
['A', 'B', 'C']


Some scores:

sage: scores[A][C]
25

sage: scores[A][A]
0


The scores as a matrix:

sage: matrix(ZZ, 3, [scores[a][b] for a in players for b in players])
[ 0 33 25]
[27  0 42]
[35 18  0]

more

I will never master Sage like you. Thanks. I will study the code. But I would like also to know the answer for the second part of the question.

( 2021-01-20 16:52:12 +0200 )edit