Search code examples
pythonsumoutput

How to get the sum of the same position in a tuple output of a for loop in python?


I wrote a definition to iterate over 200 files and calculate the number of transitions and transversions in a DNA sequence. Now I want to sum up the first column of the output of this for loop together and the second column together.

this is the output that I get repeated 200 times because I have 200 files, I want to get the sum of the first column (0+1+1+1+1+...)and the second column (1+0+0+0+....)

(0, 1) (1, 0) (1, 0) (1, 0) (1, 0) (1, 0) (1, 0) (1, 0) (1, 0) (1, 0) (0, 1) (1, 0) (0, 1) (1, 0) (0, 1) (1, 0)

I tried to print the definition as a list and then sum up the lists, but those lists are not defined as they are just a for loop output, so I couldn't sum them up.

print([dna_comparison(wild_type= f, mut_seq= h)])

Result:

[(0, 1)]
[(1, 0)]
[(1, 0)]
[(1, 0)]
[(1, 0)]
[(1, 0)]
[(1, 0)]
[(1, 0)]

Solution

  • Can be achieved by the below code:

    arr = [[(0, 1)],
    [(1, 0)],
    [(1, 0)],
    [(1, 0)],
    [(1, 0)],
    [(1, 0)],
    [(1, 0)],
    [(1, 0)]]
    firstcolumn = 0
    secondcolumn = 0  
    for i in arr:
        for v in i:
            print(v[0], ' ', v[1])
            firstcolumn = firstcolumn + v[0]
            secondcolumn = secondcolumn + v[1]
            
    print(firstcolumn, secondcolumn)
    #         7             1