Home > Software engineering >  How to insert every string character to two dimensional array
How to insert every string character to two dimensional array

Time:02-17

I've made two dimensional array

rows, columns = (5, 4)
table = [["" for i in range(columns)] for j in range(rows)]

now I want to insert every string character to it

string = "aaa bb cccc d eee"

I want this output : [['a', 'a', 'a', ''], ['b', 'b', '', 'c'], ['c', 'c', 'c', ''], ['d', '', 'e', 'e'], ['e', '', '', '']]

I tried something like this in many ways but it throws an error.

 for i in range(len(string)):
        table[columns][rows] = string[i]

CodePudding user response:

rows, columns = (5, 4)
table = [["" for i in range(columns)]for j in range(rows)]
string = "aaa bb cccc d eee"
for i in range(len(string)):
    table[i // columns][i % columns] = string[i]
print(table)

CodePudding user response:

With your table and string

rows, columns = (5, 4)
table = [['' for i in range(columns)] for j in range(rows)]
string = "aaa bb cccc d eee"

you can set elements of table to letters of string while looping rows of table.

str_iter = iter(string)
for row in table:
    for e, (_, row[e]) in enumerate(zip(row, str_iter)): ...

print(table)

Output

[['a', 'a', 'a', ' '],
 ['b', 'b', ' ', 'c'],
 ['c', 'c', 'c', ' '],
 ['d', ' ', 'e', 'e'],
 ['e', '', '', '']]

CodePudding user response:

Using numpy's array.reshape and str.ljust:

import numpy as np

mystring = "aaa bb cccc d eee"
n_rows, n_columns = (5, 4)

table = np.array(list(mystring.ljust(n_rows*n_columns))).reshape(n_rows, n_columns)

print(table)
# [['a' 'a' 'a' ' ']
#  ['b' 'b' ' ' 'c']
#  ['c' 'c' 'c' ' ']
#  ['d' ' ' 'e' 'e']
#  ['e' ' ' ' ' ' ']]

Using more_itertools' grouper, ignoring the number of rows and assuming there is less than one full row of spaces to add:

from more_itertools import grouper

mystring = "aaa bb cccc d eee"
n_columns = 4

table = list(grouper(mystring, n_columns, fillvalue=' '))

print(table)
# [('a', 'a', 'a', ' '),
#  ('b', 'b', ' ', 'c'),
#  ('c', 'c', 'c', ' '),
#  ('d', ' ', 'e', 'e'),
#  ('e', ' ', ' ', ' ')]

Using more_itertools' chunked with str.ljust:

from more_itertools import chunked

mystring = "aaa bb cccc d eee"
n_rows, n_columns = 6, 4

table = list(chunked(mystring.ljust(n_rows*n_columns), n_columns))

print(table)
# [['a', 'a', 'a', ' '],
#  ['b', 'b', ' ', 'c'],
#  ['c', 'c', 'c', ' '],
#  ['d', ' ', 'e', 'e'],
#  ['e', ' ', ' ', ' '],
#  [' ', ' ', ' ', ' ']]
  • Related