Python Program to Convert Matrix to String
Program converts a 2D matrix (list of lists) into a single string, where all the matrix elements are arranged in row-major order. The elements are separated by spaces or any other delimiter, making it easy to represent matrix data as a string.
Using List Comprehension
List comprehension provides a concise way to generate lists by applying an expression to each item in an iterable. It eliminates the need for explicit loops.
m = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
res = ' '.join([str(m[i][j]) for i in range(len(m)) for j in range(len(m[i]))])
print(res)
Output
1 2 3 4 5 6 7 8 9
Explanation
- list comprehension flattens the 2D list
mby iterating over each row (i) and each column (j) to access individual elements. join()method combines these elements into a single string, separated by spaces, after converting each element to a string.
Using Nested Loops
Nested loops iterate through each row and column of the 2D list m, accessing each element individually. The elements are converted to strings and concatenated with spaces to form the final result.
m = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
res = []
for i in range(len(m)):
for j in range(len(m[i])):
res.append(str(m[i][j]))
print(' '.join(res))
Output
1 2 3 4 5 6 7 8 9
Explanation
- Nested loops iterate through each row (
i) and each element (j) within that row, appending each element (converted to a string) to thereslist. - After the loops, the
join()method combines all elements of thereslist into a single string, separated by spaces.
Using itertools.chain
itertools.chain flattens the 2D list by chaining all inner lists together into a single iterable. The result is then converted into a string with spaces using join(), after each element is converted to a string.
import itertools
m = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
res = ' '.join(map(str, itertools.chain(*m)))
print(res)
Output
1 2 3 4 5 6 7 8 9
Explanation
itertools.chain(*m)flattens the 2D listmby chaining all its inner lists into a single iterable.map(str, ...)converts each element into a string, andjoin()combines them into a single string, separated by spaces.