0

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
2

2 Answers 2

1

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']
Sign up to request clarification or add additional context in comments.

1 Comment

Great! It was easy. Thank you!
0

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']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.