Ask Your Question
2

How can I print a 2D array in Python using ANSI formatting codes without having to iterate through every element?

asked 2021-12-25 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-07-02 13:00:00 +0000

devzero gravatar image

One way to print a 2D array in Python with ANSI formatting codes without having to iterate through every element is to use the NumPy library. NumPy is a popular Python library used for numerical computing and provides a convenient way to apply formatting codes to entire arrays.

Here is an example code snippet that demonstrates how to print a 2D NumPy array with red text:

import numpy as np

# create a 2D array
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# apply ANSI formatting codes to the entire array
red_text = '\033[31m{}\033[0m'
formatted_arr = np.array([red_text.format(val) for val in arr.flatten()]).reshape(arr.shape)

# print the formatted array
print(formatted_arr)

In this example, the NumPy flatten() method is used to convert the 2D array into a 1D array, which is then iterated over to apply the red text ANSI code to each element. The reshape() method is then used to convert the 1D array back into a 2D array with the same shape as the original. Finally, the formatted array is printed using the print() function.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-12-25 11:00:00 +0000

Seen: 8 times

Last updated: Jul 02 '21