Skip to content

Instantly share code, notes, and snippets.

@marklit
Created May 28, 2024 05:49
Show Gist options
  • Save marklit/3a72f8bcf5b9bb609b24e72095b015a8 to your computer and use it in GitHub Desktop.
Save marklit/3a72f8bcf5b9bb609b24e72095b015a8 to your computer and use it in GitHub Desktop.
More Itertools Highlights
# https://more-itertools.readthedocs.io/en/stable/index.html
list(chunked([1, 2, 3, 4, 5, 6, 7, 8], 3))
# [[1, 2, 3], [4, 5, 6], [7, 8]]
group_1, group_2 = distribute(2, [1, 2, 3, 4, 5, 6])
list(group_1) # [1, 3, 5]
list(group_2) # [2, 4, 6]
children = divide(3, [1, 2, 3, 4, 5, 6, 7])
[list(c) for c in children]
# [[1, 2, 3], [4, 5], [6, 7]]
list(split_at('abcdcba', lambda x: x == 'b'))
# [['a'], ['c', 'd', 'c'], ['a']]
iterable = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
letters, numbers = unzip(iterable)
list(letters) # ['a', 'b', 'c', 'd']
list(numbers) # [1, 2, 3, 4]
all_windows = windowed([1, 2, 3, 4, 5], 3)
list(all_windows)
# [(1, 2, 3), (2, 3, 4), (3, 4, 5)]
list(windowed([1, 2, 3, 4, 5, 6], 3, fillvalue='!', step=2))
# [(1, 2, 3), (3, 4, 5), (5, 6, '!')]
[''.join(s) for s in substrings('more')]
# ['m', 'o', 'r', 'e', 'mo', 'or', 're', 'mor', 'ore', 'more']
for item in substrings_indexes('more'):
print(item)
# ('m', 0, 1)
# ('o', 1, 2)
# ('r', 2, 3)
# ('e', 3, 4)
# ('mo', 0, 2)
# ('or', 1, 3)
# ('re', 2, 4)
# ('mor', 0, 3)
# ('ore', 1, 4)
# ('more', 0, 4)
iterable = [(1, 2), ([3, 4], [[5], [6]])]
list(collapse(iterable))
# [1, 2, 3, 4, 5, 6]
list(partial_product('AB', 'C', 'DEF'))
# [('A', 'C', 'D'), ('B', 'C', 'D'), ('B', 'C', 'E'), ('B', 'C', 'F')]
uncompressed = 'abbcccdddd'
list(run_length.encode(uncompressed))
# [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
compressed = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
list(run_length.decode(compressed))
# ['a', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'd']
is_sorted(['1', '2', '3', '4', '5'], key=int) # True
is_sorted([5, 4, 3, 1, 2], reverse=True) # False
all_unique('ABCB') # False
minmax([3, 1, 5]) # (1, 5)
obj = (1, 2, 3)
list(always_iterable(obj))
# [1, 2, 3]
obj = {'a': 1}
list(always_iterable(obj)) # Iterate over the dict's keys
# ['a']
list(always_iterable(obj, base_type=dict)) # Treat dicts as a unit
# [{'a': 1}]
from time import sleep
def generator():
yield 1
yield 2
sleep(0.2)
yield 3
iterable = time_limited(0.1, generator())
list(iterable) # [1, 2]
iterable.timed_out # True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment