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.
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
Asked: 2021-12-25 11:00:00 +0000
Seen: 8 times
Last updated: Jul 02 '21
How can popen() be used to direct streaming data to TAR?
In Python, can a string be utilized to retrieve a dataframe that has the same name as the string?
What is the method for merging field value and text into a singular line for display?
What is the method for programmatic access to a time series?