Skip to content

Instantly share code, notes, and snippets.

@svermeulen
Created January 29, 2020 11:42
Show Gist options
  • Save svermeulen/1b80cd416b5c1a897ec1352291bf19cf to your computer and use it in GitHub Desktop.
Save svermeulen/1b80cd416b5c1a897ec1352291bf19cf to your computer and use it in GitHub Desktop.
Python LINQ equivalents
def assert_throws(func):
try:
func()
except Exception:
return True
return False
def test_empty():
assert any([1, 2, 3])
assert not any([])
def test_contains():
list1 = [1, 2, 3]
assert 2 in list1
assert 4 not in list1
def test_min_max():
list1 = [0, 1, 2, 3]
assert max(list1) == 3
assert min(list1) == 0
def test_take():
from itertools import islice
values = [1, 2, 3, 4, 5]
assert list(islice(values, 2)) == [1, 2]
def test_skip():
from itertools import islice
values = [1, 2, 3, 4, 5]
assert list(islice(values, 2, None)) == [3, 4, 5]
def test_take_while():
from itertools import takewhile
list1 = [1, 2, 3, 4, 5]
assert list(takewhile(lambda c: c < 4, list1)) == [1, 2, 3]
def test_skip_while():
from itertools import dropwhile
list1 = [1, 2, 3, 4, 5]
assert list(dropwhile(lambda c: c < 4, list1)) == [4, 5]
def test_first():
list1 = [1, 2, 3, 4, 5]
assert list1[0] == 1
list2 = []
assert_throws(lambda: list2[0])
def test_first_or_default():
list1 = [1, 2, 3, 4, 5]
list2 = []
assert next(iter(list1), None) == 1
assert next(iter(list2), None) == None
def test_last():
list1 = [1, 2, 3, 4, 5]
assert list1[-1] == 5
list2 = []
assert_throws(lambda: list2[-1])
def test_single():
list1 = [1]
assert len(list1) == 1
return list1[0]
def test_count():
list1 = [1, 2, 3]
assert sum(list1) == 6
def test_where():
list1 = [0, 1, 2, 3]
assert [x for x in list1 if x >= 2] == [2, 3]
# alternatively:
assert list(filter(lambda x: x >= 2, list1)) == [2, 3]
def test_select():
list1 = [1, 2, 3]
assert list(map(lambda x: x + 1, list1)) == [2, 3, 4]
def test_group_by():
from itertools import groupby
values = ['ac', 'zd', 'xx', 'be', 'zi', 'ab', 'oo', 'bz', 'aa']
keyFunc = lambda f: f[0]
sortedValues = sorted(values, key=keyFunc)
# Convert to lists instead of iterators
groups = [(k, list(v)) for k, v in groupby(sortedValues, keyFunc)]
assert len(groups) == 5
assert groups[0][0] == 'a'
assert list(groups[0][1]) == ['ac', 'ab', 'aa']
def test_order_by():
values = ['pea', 'apple', 'orange', 'banana', 'turnip', 'cucumber', 'carrot']
assert sorted(values, key=lambda x:len(x)) == ['pea', 'apple', 'orange', 'banana', 'turnip', 'carrot', 'cucumber']
def test_distinct():
values = ['a', 'z', 'o', 'a', 'b', 'd', 'z', 'o', 'a']
values = set(values)
assert len(values) == 5
def test_zip():
values1 = ['a', 'b', 'c']
values2 = [1, 2, 3]
zipped = list(zip(values1, values2))
assert zipped[0] == ('a', 1)
assert zipped[1] == ('b', 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment