Python Split List by Filter
- 2021-12-12 09:17:33
- OfStack
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'] ]
bifurcate
Function passes through a filter
filter
The input list lst is divided into two groups. Will
filter
Middle is
True
Corresponding to the
lst
Put the item in the first list of the results, and put the
filter
Middle is
False
The entry corresponding to lst of is placed in the second list of the results.
2. enumerate
enumerate(iterable, start=0)
enumerate
The function receives 1 iterative object and returns 1 iterative object. The iterative object returns 1 tuple per iteration, and the tuple includes 1 sequence number and the iterative value of the received iterable object.
start
Parameter is used to set the initial value of the sequence number, which defaults to 0.
The example uses:
>>> 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. Table derivation
This function uses a list derivation to determine
lst
Of the position corresponding to the value inside
filter
And generate the corresponding grouping list.
A brief introduction to the list derivation can be seen: Python realizes filtering out the chapter of only 1 value in the list.