David Arteaga M.
David Arteaga M.

Reputation: 3

Matrix of sequence in Python

I have this code:

import random
def create_matrix(row, col):
    matrix = [["".join([random.choice("ATCG") for j in range(random.randint(1, 10))])
                  for _ in range(col)]
                  for _ in range(row)]
    return matrix
print(create_matrix(5, 4))

And I get this output:

[['CGCT', 'CATGC', 'GCAACTATA', 'AA'], ['TTTGGGAGTA', 'GGGCTGAA', 'GTT', 'GCTCGC'], ['ATTGT', 'CCG', 'ACC', 'GTG']

How can I get the same output but arranged in a matrix 3x4? Something like this but with the previous output.

1   2   3   4
5   6   7   8
9   10  11  12
13  14  15  16
17  18  19  20

Upvotes: 0

Views: 316

Answers (2)

Ftagliacarne
Ftagliacarne

Reputation: 800

If you use numpy, the output will be better formatted. But basically what you have is correct, it's just a matter of the code is outputted.

import numpy as np
print(np.array(create_matrix(5, 4)))

Will produce the following output:

[['CT' 'CA' 'CCAGTG']
 ['ACAGAA' 'AAT' 'C']
 ['ATCCAGAA' 'ATCGACCGTG' 'T']
 ['GACA' 'AACCGTAG' 'GCCACAGAC']
 ['TCAATT' 'TTTCAG' 'TACGCCTGA']]

Upvotes: 0

Ewan Brown
Ewan Brown

Reputation: 637

If you're not concerned about spacing things nicely, a simple for loop to print each row at a time would work. (Try Online)

import random
def create_matrix(row, col):
    matrix = [["".join([random.choice("ATCG") for j in range(random.randint(1, 10))])
                  for _ in range(col)]
                  for _ in range(row)]
    return matrix

matrix = create_matrix(5, 4)

for r in matrix:
    print(r)

With output:

['TTTG', 'TCT', 'ACTCGAGCTA', 'AA']
['TTAC', 'GT', 'T', 'CGGAC']
['GGCATGT', 'CCCTCCGTCC', 'GTCGAA', 'GTCATGTAG']
['TC', 'TTACGGTCT', 'TGGCAAAA', 'AGCCGGGGA']
['A', 'C', 'CT', 'AA']

Upvotes: 1

Related Questions