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
Selected Reading
Conversion to N*N tuple matrix in Python
When working with tuples in Python, you might need to convert an N*N tuple structure into a matrix format by padding shorter tuples with zeros. This can be accomplished using a simple loop and the * operator to repeat values.
The * operator in Python can multiply values and also repeat elements. For example, (0,) * 3 creates (0, 0, 0).
Converting Tuple to N*N Matrix
Here's how to pad tuples with zeros to create a uniform matrix structure ?
my_tuple_1 = ((11, 14), (0, 78), (33, 11), (10, 78))
print("The tuple of tuple is:")
print(my_tuple_1)
N = 4
print("The value of N has been initialized to " + str(N))
my_result = []
for tup in my_tuple_1:
my_result.append(tup + (0,) * (N - len(tup)))
print("The tuple after filling in the values is:")
print(my_result)
The tuple of tuple is: ((11, 14), (0, 78), (33, 11), (10, 78)) The value of N has been initialized to 4 The tuple after filling in the values is: [(11, 14, 0, 0), (0, 78, 0, 0), (33, 11, 0, 0), (10, 78, 0, 0)]
How It Works
The conversion process involves these steps:
- A nested tuple is defined containing 4 inner tuples, each with 2 elements
- N is set to 4 to create a 4×4 matrix structure
- An empty result list stores the padded tuples
- For each tuple, zeros are appended using
(0,) * (N - len(tup)) - Since each inner tuple has length 2,
(N - 2) = 2zeros are added - The concatenated tuples form uniform 4-element rows
Alternative with Different Sizes
This approach works with tuples of varying lengths ?
mixed_tuples = ((1, 2, 3), (4, 5), (6,), (7, 8, 9, 10))
N = 5
print("Original tuples:")
print(mixed_tuples)
result = []
for tup in mixed_tuples:
padded = tup + (0,) * (N - len(tup))
result.append(padded)
print(f"\nPadded to {N}x{N} matrix:")
for row in result:
print(row)
Original tuples: ((1, 2, 3), (4, 5), (6,), (7, 8, 9, 10)) Padded to 5x5 matrix: (1, 2, 3, 0, 0) (4, 5, 0, 0, 0) (6, 0, 0, 0, 0) (7, 8, 9, 10, 0)
Conclusion
Use tuple concatenation with the * operator to pad tuples with zeros and create uniform matrix structures. This technique is useful for data preprocessing and matrix operations in Python.
Advertisements
