Filter 2D tuples using python list comprehension

  • Tuples are a group of items enclosed within ().
    List comprehension can be used to filter a single-dimensional tuple.
    After applying filter, we can get the output as a list or a tuple.
    Below code illustrates how to filter a tuple of numbers, strings or dates.

    Copied
    from datetime import datetime
    
    numtuple = (5, 10, 20, 30, 40)
    #Filter numbers from tuple
    filterednumtuple = [num for num in numtuple if num > 15]
    print("Filtered tuple of numbers: " + str(tuple(filterednumtuple)))
    
    strtuple = ('James', 'Rory', 'Kevin')
    #Filter name Rory and Kevin
    filteredstrtuple = (st for st in strtuple if (st == 'Rory' or st == 'Kevin'))
    print("Filtered tuple of names: " + str(tuple(filteredstrtuple)))
    
    datetuple = ('2021/1/2', '2021/1/15', '2022/4/1', '2022/5/2')
    #Convert string dates to datetime objects
    dttuple = (datetime.strptime(dt, '%Y/%m/%d') for dt in datetuple)
    #Apply filter by month
    filtereddatetuple = (dt for dt in dttuple if dt.month == 1)
    #Convert datetime to str dates, if needed
    dates2strtuple = (datetime.strftime(dt1, '%Y/%m/%d')  for dt1 in filtereddatetuple)
    print("Filtered dates tuple: " + str(tuple(dates2strtuple)))
    
    Output:
      Filtered tuple of numbers: (20, 30, 40)
      Filtered tuple of names: ('Rory', 'Kevin')
      Filtered dates tuple: ('2021/01/02', '2021/01/15')

    Check this sample if dates are having multiple formats.
    Filter a list of string dates in different formats

  • Two-dimensional tuples

    If tuples are two-dimensional(tuples within tuples), some additional changes are required in the filter.
    We have to access items within the tuple using positional parameters.
    Output can be single or two-dimensional tuple.

    Copied
    from datetime import datetime
    
    numtuple = ( (1, 5), (2, 10), (3, 20), (4, 30), (5, 50) )
    #Filter numbers. First part > 2 and second < 50
    filterednum = ( (v[0], v[1]) for v in numtuple if (v[0] > 2 and v[1] < 50) )
    print(tuple(filterednum))
    
    strtuple = ( (1, 'Abe'), (2, 'Kim'), (3, 'Dan') )
    #Filter names with 'a'
    filteredstr = (s[1] for s in strtuple if ('a' in s[1].lower()) )
    print(tuple(filteredstr))
    
    datetuple = ( (1, '2020/10/15'), (2, '2020/10/15'), (3, '2022/04/10'), (4, '2022/02/05') )
    #String dates to datetime objects to apply filter
    dtitems = ( (d[0], datetime.strptime(d[1], '%Y/%m/%d')) for d in datetuple )
    #Filter by year
    filtereddates = (d for d in dtitems if d[1].year == 2022)
    #Datetime to string dates conversion
    dates2str = ( (d[0], datetime.strftime(d[1], '%Y/%m/%d'))  for d in filtereddates)
    print(tuple(dates2str))
    
    Output:
      ((3, 20), (4, 30))
      ('Abe', 'Dan')
      ((3, '2022/04/10'), (4, '2022/02/05'))
Absolute Code Works - Python Topics