'How to write grid in csv file in python

I have a list of tuples. Each tuple contain 2 values, together with the results of an operation between the two values. Here is an example:

my_list = [(1,1,1.0), (1,2,0.8), (1,3,0.3), (2,1,0.8), (2,2,1.0), (2,3,0.5), (3,1,0.3), (3,2,0.5), (3,3,1.0)]

I need to store this value in a csv file so that they look like this:

0    1     2     3
1    1    0.8   0.3
2   0.8    1    0.5
3   0.3   0.5    1

In other words, I need to go to a new row every time the first number of the tuple change.

This is the function I am currently using, which writes each tuple in a new row (not what I want):

def write_csv(my_list, fname = ''):
    with open (fname, mode='a+') as f:
        f_writer = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
        for x in my_list:
            f_writer.writerow([str(x[0]), str(x[1]), str(x[2])])

Any suggestion on how to modify (rewrite from scratch) it?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source