Filter a 3D list using python list comprehension
-
List comprehensions can be applied on lists of any level to filter, update, etc.
Here we will do a sample on a 3 dimensional list.
Same logic can be applied on lists of any dimension for a cleaner code.Copiedfrom datetime import datetime numlist = [ [1, 5, [100, 200] ], [2, 10, [300, 400] ], [3, 20, [500, 600], 40 ,50 ], [4, 30, [700, 800], 60, 70, 80 ] ] #Filter condition is using first level of the list filterednumlist = [ num for num in numlist if len(num) < 3 ] print(filterednumlist) #Filter condition is using second level of the list filterednumlist = [ num for num in numlist if num[0] > 3 ] print(filterednumlist) #Filter condition is using third level of the list filterednumlist = [ [num[0], num[1], num[2]] for num in numlist if (num[2][0] < 300) ] print(filterednumlist)
[ [3, 20, [500, 600], 40, 50], [4, 30, [700, 800], 60, 70, 80] ] [ [1, 5, [100, 200]], [2, 10, [300, 400]] ] [ [3, 20, [500, 600]], [4, 30, [700, 800]] ]
To update a multi-dimensional list, refer this sample.
Update a multi-dimensional list using list comprehension