Update formatting in every_nth Update formatting in shuffle Update formatting in has_duplicates Update formatting in group_by Update formatting in sum_by Update formatting in zip Update formatting in longest_item Update formatting in bifurcate_by Update formatting in difference_by Update formatting in clamp_number Update formatting in min_by Update formatting in max_by Update formatting in union Update formatting in n_times_string Update formatting in check_prop Update formatting in chunk Update formatting in transpose Update formatting in bifurcate Update formatting in union_by Update formatting in initialize_list_with_range Update formatting in most_frequent
25 lines
611 B
Markdown
25 lines
611 B
Markdown
---
|
|
title: bifurcate_by
|
|
tags: list,function,intermediate
|
|
---
|
|
|
|
Splits values into two groups according to a function, which specifies which group an element in the input list belongs to.
|
|
If the function returns `True`, the element belongs to the first group; otherwise, it belongs to the second group.
|
|
|
|
Use list comprehension to add elements to groups, based on `fn`.
|
|
|
|
```py
|
|
def bifurcate_by(lst, fn):
|
|
return [
|
|
[x for x in lst if fn(x)],
|
|
[x for x in lst if not fn(x)]
|
|
]
|
|
```
|
|
|
|
```py
|
|
bifurcate_by(
|
|
['beep', 'boop', 'foo', 'bar'],
|
|
lambda x: x[0] == 'b'
|
|
) # [ ['beep', 'boop', 'bar'], ['foo'] ]
|
|
```
|