From c22e12e22f0bc7d78bcdec90fd9731f1a7f17bec Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Tue, 20 Aug 2019 12:37:06 +0300 Subject: [PATCH] Add bifurcate snippet --- snippets/bifurcate.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 snippets/bifurcate.md diff --git a/snippets/bifurcate.md b/snippets/bifurcate.md new file mode 100644 index 000000000..2538d8728 --- /dev/null +++ b/snippets/bifurcate.md @@ -0,0 +1,21 @@ +--- +title: bifurcate +tags: list,intermediate +--- + +Splits values into two groups. +If an element in `filter` is `True`, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group. + +Use list comprehension and `enumerate()` to add elements to groups, based on `filter`. + +```py +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] + ] +``` + +```py +bifurcate(['beep', 'boop', 'foo', 'bar'], [True, True, False, True]) # [ ['beep', 'boop', 'bar'], ['foo'] ] +```