Skip to content

Instantly share code, notes, and snippets.

@carlos-jenkins
Last active November 4, 2019 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlos-jenkins/53b089d98b6e8e1461eafd8103bd4628 to your computer and use it in GitHub Desktop.
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.
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