Filter two dimensional list using python list comprehension
-
For a single dimensional list in python, applying filter using list comprehension is easy. We just need to apply filter on the list as in sample below. This sample shows how to filter a list of numbers, strings or dates.
Copiedfrom datetime import datetime numlist = [1, 5, 3, 8, 15, 20, 25, 28] #Filter numbers greater than 15 filterednumlist = [num for num in numlist if num > 15] print("Greater than 15: " + str(filterednumlist)) strlist = ['John', 'Ted', 'Lisa'] #Filter names Ted and Lisa filteredstrlist = [st for st in strlist if (st == 'Ted' or st == 'Lisa')] print("Names Filtered: " + str(filteredstrlist)) datelist = ['2020/10/15', '2020/10/15', '2021/04/10', '2022/02/05', '2022/02/05'] #Convert string dates to datetime objects before filter dtlist = [datetime.strptime(dt, '%Y/%m/%d') for dt in datelist] #Apply filter by year filtereddatelist = [dt for dt in dtlist if dt.year == 2022] #Convert datetime to string dates, if needed dateslist2str = [datetime.strftime(dt1, '%Y/%m/%d') for dt1 in filtereddatelist] print("Dates of year 2022: " + str(dateslist2str))
Greater than 15: [20, 25, 28]
Names Filtered: ['Ted', 'Lisa']
Dates of year 2022: ['2022/02/05', '2022/02/05']In the above example, input dates are in same format.
If the list of dates are in different format, strptime() can't be used directly.
Refer below link if you have this requirement, to know how to do this.
Filter a list of string dates in different formats -
Lists within list
If the list contains lists within, filter can be applied in a slightly different way.
Samples below.Here we are using 2 dimensional lists. Filter can be applied on the items in zeroth or first position. Output can be single or 2 dimensional list as shown in the samples.
Copiedfrom datetime import datetime numlist = [ [1, 5], [2, 10], [3, 20], [4, 30], [5, 50] ] #Filter numbers. First part > 2 and second < 50 filterednumlist = [ [num[0], num[1]] for num in numlist if (num[0] > 2 and num[1] < 50) ] print("Filtered List: " + str(filterednumlist)) strlist = [ [1, 'John'], [2, 'Ted'], [3, 'Lisa'] ] #Filter names Ted and Lisa filteredstrlist = [st[1] for st in strlist if (st[1] == 'Ted' or st[1] == 'Lisa')] print("Filtered List: " + str(filteredstrlist)) datelist = [ [1, '2020/10/15'], [2, '2020/10/15'], [3, '2021/04/10'], [4, '2022/02/05'] ] #Convert string dates to datetime objects before filter dtlist = [ [dt[0], datetime.strptime(dt[1], '%Y/%m/%d')] for dt in datelist] #Apply filter by year filtereddatelist = [dt for dt in dtlist if dt[1].year == 2022] #Convert datetime to string dates, if needed dateslist2str = [ [dt1[0], datetime.strftime(dt1[1], '%Y/%m/%d')] for dt1 in filtereddatelist] print("Dates of year 2022: " + str(dateslist2str))
Filtered List: [[3, 20], [4, 30]]
Filtered List: ['Ted', 'Lisa']
Dates of year 2022: [[4, '2022/02/05']]