asher asher - 3 months ago 18
Python Question

How to extract columns from multiple rows in Python using nested loops?

I have a list with 3 sequences

seq_list = ['ACGT', 'ATTT', 'ACCC']


I want to extract the columns from the the list and store it in another list using nested loops in python

The final output should be

seq_list = ['AAA', 'CTC', 'GTC','TTC']


I have written the following code, but it does not yield the desired output.

column = []
for i in range(len(seq_list[0])): #Length of the row
for j in range(len(seq_list)): #Length of the column
column.append(seq_list[j][i])
print column

Answer

By your method I made little modification, for each inner for loop i created a string and then after inner for loop ends i appended it to column:

seq_list = ['ACGT', 'ATTT', 'ACCC']
column = []
for i in range(len(seq_list[0])):   #Length of the row
    string = ""
    for j in range(len(seq_list)):    #Length of the column
        string += seq_list[j][i]
    column.append(string)
print column

Output:

['AAA', 'CTC', 'GTC', 'TTC']

Although you could use @alecxe code(using zip and join). I think it's cool and more pythonic.