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
Ewan Brown
  • 640
  • 3
  • 12
  • [duplicated] https://stackoverflow.com/questions/17870612/printing-a-two-dimensional-array-in-python – Glauco Oct 07 '21 at 15:12
  • Here there are some useful trick: https://www.delftstack.com/howto/python/print-matrix-python/ – Glauco Oct 07 '21 at 15:13

2 Answers2

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']
Ewan Brown
  • 640
  • 3
  • 12
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']]
Ftagliacarne
  • 675
  • 8
  • 16