Last active
November 4, 2019 20:17
-
-
Save carlos-jenkins/53b089d98b6e8e1461eafd8103bd4628 to your computer and use it in GitHub Desktop.
Split a collection in two parts as defined by the given criteria.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def split(iterable, criteria=lambda e: e): | |
""" | |
Split a collection in two parts as defined by the given criteria. | |
Usage:: | |
>>> split([1,2,3,4,5,6], lambda e: e > 2) | |
([3, 4, 5, 6], [1, 2]) | |
By default, the element itself is used as the criteria:: | |
>>> split([0, 1, [], [0], [1], (), (0,), (1,), 0.0, 1.0, {}, None, True, False]) | |
([1, [0], [1], (0,), (1,), 1.0, True], [0, [], (), 0.0, {}, None, False]) | |
:param iterable: An iterable collection. | |
:param criteria: A function that receives an element of the collection and | |
determines if place it on left (if returns Trueish) or right | |
(if returns Falseish). Signature is expected to be:: | |
def mycriteria(element): | |
return element > 5 | |
Or using lambda:: | |
lambda e: e > 5 | |
:return: A tuple with two lists, left (True) and right (False). | |
:rtype: tuple | |
""" # noqa | |
left = [] | |
right = [] | |
for element in iterable: | |
if criteria(element): | |
left.append(element) | |
continue | |
right.append(element) | |
return left, right |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment