SoFunction
Updated on 2024-12-20

Python Splits Lists Based on Filters

1. bifurcate

def bifurcate(lst, filter):
  return [
    [x for i, x in enumerate(lst) if filter[i] == True],
    [x for i, x in enumerate(lst) if filter[i] == False]
  ]

# EXAMPLES
bifurcate(['beep', 'boop', 'foo', 'bar'], [True, True, False, True]) # [ ['beep', 'boop', 'bar'], ['foo'] ]


bifurcateThe function is passed through a filterfilterThe definition divides the input list lst into two groups. The input list lst is divided into two groups by placing thefilterhit the nail on the headTruecorrespondinglstitem into the first list of results, placing thefilterhit the nail on the headFalseof the corresponding lst item into the second list of results.

2. enumerate

enumerate(iterable, start=0)


enumerateThe function receives an iterable object and returns an iterable object. The iterable object returns a tuple for each iteration, which consists of a serial number and the iteration value of the received iterable object.startparameter is used to set the initial value of the serial number, the default is 0.

Example use for:

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]


The implementation logic of the enumerate function is equivalent to the following code:

def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1

3. Tabular derivatives

This function uses a list-deductive judgmentlstThe value in the corresponding position of thefiltervalues and generates a list of corresponding groupings.

A brief introduction to list derivatives can be viewed:Python implementation of filtering out unique values in listsThe chapters.

to this article on Python according to the filter split list of the article is introduced to this, more related Python according to the filter split list content please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more!