Python – 3D Matrix to Coordinate List

PythonServer Side ProgrammingProgramming

When it is required to convert a three dimensional matrix into a co-ordinate list, the ‘zip’ method, and a list comprehension are used.

Example

Below is a demonstration of the same −

my_list_1 = [[['He', 'Wi'], ['llo', 'll']], [['Pyt', 'i'], ['hon', 'sFun']], [['Ho', 'g'], ['pe', 'ood']]]

print("The list is : ")
print(my_list_1)

my_list_1.sort()
print("The list after sorting is ")
print(my_list_1)
my_result = [ele for sub_elem_1, sub_elem_2 in my_list_1 for ele in zip(sub_elem_1,
sub_elem_2)]
print("The resultant list is : ")
print(my_result)

Output

The list is :
[[['He', 'Wi'], ['llo', 'll']], [['Pyt', 'i'], ['hon', 'sFun']], [['Ho', 'g'], ['pe', 'ood']]]
The list after sorting is
[[['He', 'Wi'], ['llo', 'll']], [['Ho', 'g'], ['pe', 'ood']], [['Pyt', 'i'], ['hon', 'sFun']]]
The resultant list is :
[('He', 'llo'), ('Wi', 'll'), ('Ho', 'pe'), ('g', 'ood'), ('Pyt', 'hon'), ('i', 'sFun')]

Explanation

  • A list of list of list is defined, and displayed on the console.

  • It is sorted in the ascending order, and displayed on the console.

  • A list comprehension is used to iterate the list where the sub elements are zipped, and the respective elements from consecutive lists are grouped together.

  • This is converted to a list and assigned to a variable.

  • This is displayed as the output on the console.

raja
Updated on 13-Sep-2021 07:22:19

Advertisements