Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Add custom borders to a matrix in Python
When it is required to add custom borders to the matrix, a simple list iteration can be used to add the required borders to the matrix. This technique is useful for displaying matrices in a more readable format with visual boundaries.
Example
Below is a demonstration of the same ?
my_list = [[2, 5, 5], [2, 7, 5], [4, 5, 1], [1, 6, 6]]
print("The list is :")
print(my_list)
print("The resultant matrix is :")
border = "|"
for sub in my_list:
my_temp = border + " "
for ele in sub:
my_temp = my_temp + str(ele) + " "
my_temp = my_temp + border
print(my_temp)
The list is : [[2, 5, 5], [2, 7, 5], [4, 5, 1], [1, 6, 6]] The resultant matrix is : | 2 5 5 | | 2 7 5 | | 4 5 1 | | 1 6 6 |
How It Works
A list of lists is defined and displayed on the console.
A value for the 'border' is defined using the pipe character "|".
The outer list is iterated over, and for each row, the border is concatenated with a space.
Each element in the row is converted to string and concatenated with spaces.
Finally, the closing border is added and the formatted row is displayed.
Using Different Border Characters
You can customize the border character to create different visual effects ?
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
borders = ["*", "#", "+", "="]
for i, border_char in enumerate(borders):
print(f"Using '{border_char}' as border:")
for row in matrix:
row_str = border_char + " "
for element in row:
row_str += str(element) + " "
row_str += border_char
print(row_str)
print()
Using '*' as border: * 1 2 3 * * 4 5 6 * * 7 8 9 * Using '#' as border: # 1 2 3 # # 4 5 6 # # 7 8 9 # Using '+' as border: + 1 2 3 + + 4 5 6 + + 7 8 9 + Using '=' as border: = 1 2 3 = = 4 5 6 = = 7 8 9 =
Conclusion
Adding custom borders to matrices in Python involves iterating through each row and concatenating border characters with proper spacing. This technique enhances the visual representation of matrix data and can be customized with different border characters for various display needs.
