If I understand what you are trying to do; find the most common character in each column(?) here is how you can do it:
def most_common(col, exclude_char='N'):
col = list(filter((exclude_char).__ne__, col))
return max(set(col), key=col.count)
sequences = []
with open('DNAinput.txt', 'r') as file:
for line in file:
if line[0] == '>':
continue
else:
sequences.append(line.strip())
m = max([len(v) for v in sequences])
matrix = [list(v) for v in sequences]
for seq in matrix:
seq.extend(list('N' * (m - len(seq))))
transposed_matrix = [[matrix[j][i] for j in range(len(matrix))] for i in range(m)]
for column in transposed_matrix:
print(most_common(column))
This works by:
Opening your file and reading it into a list like this:
# This is the `sequences` list
['GATCA', 'AATC', 'AATA', 'ACTA']
Get the length of the longest DNA sequence:
# m = max([len(v) for v in sequences])
5
Create a matrix (list of lists) from these sequences:
# matrix = [list(v) for v in sequences]
[['G', 'A', 'T', 'C', 'A'],
['A', 'A', 'T', 'C'],
['A', 'A', 'T', 'A'],
['A', 'C', 'T', 'A']]
Pad the matrix so all the sequences are the same length:
# for seq in matrix:
# seq.extend(list('N' * (m - len(seq))))
[['G', 'A', 'T', 'C', 'A'],
['A', 'A', 'T', 'C', 'N'],
['A', 'A', 'T', 'A', 'N'],
['A', 'C', 'T', 'A', 'N']]
Transpose the matrix so columns go top -> bottom (not left -> right). This places all the characters from the same position into a list together.
# [[matrix[j][i] for j in range(len(matrix))] for i in range(m)]
[['G', 'A', 'A', 'A'],
['A', 'A', 'A', 'C'],
['T', 'T', 'T', 'T'],
['C', 'C', 'A', 'A'],
['A', 'N', 'N', 'N']]
Finally, iterate over each list in the transposed matrix and call most_common with the sub-list as input:
# for column in transposed_matrix:
# print(most_common(column))
A
A
T
C
A
There are caveats to this approach; firstly, the most_common function I have included will return the first value in the event that there are the same number of nucleotides in a single postion (see position four, this could have been either A or C). Furthermore, the most_common function could take exponentially more time than using Counter from collections.
For these reasons, I would strongly recommend using the following script instead as collections is included with python on installation.
from collections import Counter
sequences = []
with open('DNAinput.txt', 'r') as file:
for line in file:
if line[0] == '>':
continue
else:
sequences.append(line.strip())
m = max([len(v) for v in sequences])
matrix = [list(v) for v in sequences]
for seq in matrix:
seq.extend(list('N' * (m - len(seq))))
transposed_matrix = [[matrix[j][i] for j in range(len(matrix))] for i in range(m)]
for column in transposed_matrix:
print(Counter(column).most_common(5))