Python | Convert Character Matrix to single String

Python | Convert Character Matrix to single String

Converting a matrix (2D list) of characters into a single string can be achieved using list comprehensions and string methods. Depending on the desired order (e.g., row-major or column-major), the approach may slightly vary.

Problem Statement:

Given a 2D list (matrix) of characters, convert it into a single string.

Example Input: Matrix:

[ ['H', 'e', 'l'], ['l', 'o', 'W'], ['o', 'r', 'l'], ['d', '!', ' '] ] 

Example Output (Row-major order): String: "HelloWorld! "

Example Output (Column-major order): String: "Hloed!eolrWl "

Python Code:

Here's how you can achieve both transformations:

def matrix_to_string_row_major(matrix): # Flatten the matrix in row-major order and join characters to form a string return ''.join([''.join(row) for row in matrix]) def matrix_to_string_column_major(matrix): # Flatten the matrix in column-major order and join characters to form a string return ''.join([''.join(matrix[row][col] for row in range(len(matrix))) for col in range(len(matrix[0]))]) # Example usage: char_matrix = [ ['H', 'e', 'l'], ['l', 'o', 'W'], ['o', 'r', 'l'], ['d', '!', ' '] ] result_row_major = matrix_to_string_row_major(char_matrix) print("Row-major:", result_row_major) # Output: "HelloWorld! " result_column_major = matrix_to_string_column_major(char_matrix) print("Column-major:", result_column_major) # Output: "Hloed!eolrWl " 

Explanation:

  1. matrix_to_string_row_major: We use a list comprehension to join each row of characters into strings. Then, we join all these smaller strings to form the final string in row-major order.

  2. matrix_to_string_column_major: We first iterate over the columns of the matrix. For each column, we extract characters from every row to construct a string. Then, we join all these column-based strings to form the final string in column-major order.

Both functions make use of Python's powerful list comprehensions and string join methods to achieve the desired transformations efficiently.


More Tags

apache-spark-2.0 maven-ant-tasks shopify-app signal-handling vue-loader form-control custom-pages linq-to-sql android-radiogroup mixins

More Programming Guides

Other Guides

More Programming Examples