Skip to content

Instantly share code, notes, and snippets.

@tuxdna
Created May 7, 2024 10:46
Show Gist options
  • Save tuxdna/ab82461985646c1d93a7923808f2fd96 to your computer and use it in GitHub Desktop.
Save tuxdna/ab82461985646c1d93a7923808f2fd96 to your computer and use it in GitHub Desktop.
Python itertools example
# run tests uisng: pytest -vv combine_lists.py
from typing import List, Any
import itertools
def combine_lists_of_lists(*args: List[List[Any]]) -> List[List[Any]]:
results = [list(itertools.chain(*tup))
for tup in itertools.zip_longest(*args, fillvalue=[])]
return results
def test_1():
list1 = [["a"], [1]]
list2 = [["b"], [2]]
assert combine_lists_of_lists(list1, list2) == [["a", "b"], [1, 2]]
def test_2():
list1 = [["a"], [1]]
list2 = []
list3 = [["b"], [2]]
assert combine_lists_of_lists(list1, list2, list3) == [["a", "b"], [1, 2]]
def test_3():
list1 = [["a", "b"], [1, 2]]
list2 = []
list3 = [["c"], [3, 4]]
assert combine_lists_of_lists(list1, list2, list3) == [["a", "b", "c"], [1, 2, 3, 4]]
def combine_lists_of_lists_original(*args):
results = []
for rows in args:
for i, x in enumerate(rows):
if len(results) <= i:
results.append(x)
else:
results[i].extend(x)
return results
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment